按特定值从通用列表中获取所有项目

时间:2019-08-12 11:47:34

标签: list linq c#-4.0

我有一个通用清单,其中有很多物品。那里有些项目具有像true这样的特定值,在这里,我需要运行一个linq查询,以使基于value = true的那些特定项目能够隔离在var变量中。

我尝试使用List.Find,FindAll,包含

public class FilterControl  
{  
    public bool IsItem1 { get; set; }  
    public bool IsItem2 { get; set; }  
    public bool IsItem3 { get; set; }  
    public bool IsItem4 { get; set; }  
    public bool IsItem5 { get; set; }  
    public bool IsItem6 { get; set; }  
    public bool IsItem7 { get; set; }  
    public bool IsItem8 { get; set; }  
    public bool IsItem9 { get; set; }  
    public bool IsItem10 { get; set; }  
}  

List<FilterControl> listFilters = new List<FilterControl>(){  
   new FilterControl() { IsItem1 = false, IsItem2 = false, IsItem3 = true, IsItem4 = false, IsItem5 = true, IsItem6 = true, IsItem7 = false, IsItem8 = true, IsItem9 = false, IsItem2 = true },  
}; 

我尝试过如下操作:

var getAllItemsWchValueTrue = listFilters.Where(a => a.IsItem1 == true).Select(a => a.IsItem1).FirstOrDefault();

但是在这段代码中,我只能检查一个值为true或false的项目。 我需要在这里检查哪些值具有true,而我要在Var变量中包含哪些项。

2 个答案:

答案 0 :(得分:1)

检查这个小提琴 https://dotnetfiddle.net/kjvWPC

onunload

更整洁的方式https://dotnetfiddle.net/6dxa17

    List<FilterControl> listFilters = new List<FilterControl>(){
   new FilterControl() { IsItem1 = false, IsItem2 = false, IsItem3 = true, IsItem4 = false, IsItem5 = true, IsItem6 = true, IsItem7 = false, IsItem8 = true, IsItem9 = false }};

    var getAllItemsWchValueTrue  =  listFilters.Select(p=>
            {

         List<string> items =new List<string>();
        foreach (PropertyInfo prop in p.GetType().GetProperties()){
         var type = Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType;
         if (type == typeof (System.Boolean) && (bool)prop.GetValue(p, null))
         { 
            items.Add(prop.Name);
         }
        }

        return items;
       }).SelectMany(q=> q);

答案 1 :(得分:0)

我相信您正在寻找Enumerable.Where。您可以提交lambda表达式作为参数,以按特定属性进行过滤。