我有一个从ProfileBase派生的列表.此列表可以包含Profile,DynamicViewProfile的实例,因为它们都是从ProfileBase派生的
但是如果项目类型是DynamicViewProfile,我必须使用NodeName,如果是Profile,那么我应该使用DocName
profileListsForSearch = profileLists.Where(stringToCheck =>
((Profile)stringToCheck).DocName.Contains(searchBar.Text)).ToList();
Run Code Online (Sandbox Code Playgroud)
所以这是用于配置文件,它没关系,但如果列表包含DynamicViewProfile对象,那么我有一个例外,因为docname为null我需要获取NodeName
我希望我的问题很清楚
这里没有什么特别的LINQ - 你基本上编写的代码与正常情况相同,使用is或as:
string searchText = searchBar.Text;
profileListsForSearch = profileLists
.Where(profile =>
profile is Profile
? ((Profile)profile).DocName.Contains(searchText)
: ((DynamicViewProfile)profile).NodeName.Contains(searchText))
.ToList();
Run Code Online (Sandbox Code Playgroud)
这是假设这是涉及的唯一两种类型.如果你的列表包含其他类型,你会得到一个InvalidCastException.
然而,这是很丑陋-感觉ProfileBase应该揭露一些属性或方法指示的总称-然后可以实施返回DocName中Profile和NodeName的DynamicViewProfile.然后你只需要:
string searchText = searchBar.Text;
profileListsForSearch = profileLists
.Where(profile => profile.Name.Contains(searchText))
.ToList();
Run Code Online (Sandbox Code Playgroud)
它在添加新子类方面也具有前瞻性ProfileBase- 并且通常更清晰地使用多态性.每次你需要施放 - 特别是有条件地施放到一个或另一个 - 考虑一个共同的方法/属性是否可行,使其更清洁.
| 归档时间: |
|
| 查看次数: |
72 次 |
| 最近记录: |