基于KeyValuePairs的过滤器列表 [英] Filter list based on KeyValuePairs
问题描述
我有一个要基于KeyValuePairs列表进行过滤的列表. KeyValuePair中的所有键都存在于对象中.
I have a list that i would like to filter based on a List of KeyValuePairs. All the keys in the KeyValuePair exist in the object.
因此,假设我有一个此类的对象列表:
So let's say i have a list of objects from this class:
public class filters
{
public string Name { get; set; }
public string Age { get; set; }
public string Country { get; set; }
}
我有一个KeyValuePair与:
And I have a KeyValuePair with:
Key: "Name", Value: "test"
Key: "Country", Value: "SE"
是否可以从KeyValuePair生成某种类型的LINQ谓词,并将其用作list.Where(predicate)
,并且该谓词与我写过list.Where(c => c.Name == "test" && c.Country == "SE")
的谓词相同?
Is it possible to generate some kind of LINQ predicate from the KeyValuePair that is usable as list.Where(predicate)
, and the predicate would be the same as if I would have written list.Where(c => c.Name == "test" && c.Country == "SE")
?
或者我应该如何处理?
推荐答案
单线:
var filters = new Dictionary<string, string>{{"Name", "test"}, {"Country", "SE"}};
var result = list.Where(item => filters.All(f => (string)(item.GetType().GetProperty(f.Key)?.GetValue(item)) == f.Value));
这使您拥有无限数量的过滤器.
This enables you to have an unlimited number of filters.
对于list
中的每个item
,All
谓词将检查每个过滤器的有效性. item.GetType()
为您的item
获取Type
(即有关您班级的信息). GetProperty(f.Key)
获取有关特定属性的信息,该属性由当前过滤器f
的Key
命名. GetValue(item)
获取当前item
的属性的值. ?
是c#6的新功能,即它是对null
的内联检查,即,如果未找到该属性,则它不会尝试执行GetValue
-这会引发NullReferenceException
-但返回null
.然后,您必须将属性值转换为string
并将其与当前过滤器的Value
进行比较.您也可以使用String :: Compare(或您喜欢的任何其他比较方法).
For each item
in your list
the All
predicate will check the validity for each filter. item.GetType()
gets the Type
(ie information about your class) for your item
. GetProperty(f.Key)
gets information for the specific property, named by the Key
of the current filter f
. GetValue(item)
gets the value of the property for the current item
. The ?
is a new feature of c# 6, ie it's an inline check for null
, ie if the property is not found, it does not try to execute GetValue
-- which would raise a NullReferenceException
-- but returns null
. You then have to cast the property value to string
and compare it to the Value
of the current filter. You can also use String::Compare (or any other comparison method you prefer).
All
仅在满足所有过滤器条件时返回true
,否则返回false.因此,此查询的结果将包含符合字典中所有过滤条件的所有元素
All
only returns true
if all filters are met and false otherwise. So the result of this query will contain all elements which meet all the filters in your Dictionary
这篇关于基于KeyValuePairs的过滤器列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!