假设我有一个这样的类:
public class SampleClass
{
public string SampleProperty1 { get; set; }
public string SampleProperty2 { get; set; }
public string SampleProperty3 { get; set; }
public string SampleProperty4 { get; set; }
public string SampleProperty5 { get; set; }
}
我有一个这样的清单:
List<SampleClass> sampleList = new List<SampleClass>();
我想通过SampleProperty1
和过滤该列表SampleProperty5
。下次我会使用SampleProperty3
or SampleProperty2
。我的意思是用户可以按他想要的任何属性进行过滤。
我怎样才能实现这种灵活性?
我不想编写与属性一样多的 if 语句,因为实际的属性数量要多得多。
有没有聪明的方法来做到这一点?
谢谢。
您可以为每个属性构建 lambda 表达式并使用它过滤集合。假设您有Dictionary
一些属性名称及其要过滤的值:
var filters = new Dictiontionary<string, object>();
IEnumerable<SampleClass> query = listOfSampleClasses;
// we will loop through the filters
foreach(filter in filters)
{
// find the property of a given name
var property = typeof(SampleClass).GetProperty(filter.Key, BindingFlags.Instance | BindingFlags.Public);
if (property == null) continue;
// create the ParameterExpression
var parameter = Expression.Parameter(typeof(SampleClass));
// and use that expression to get the expression of a property
// like: x.SampleProperty1
var memberExpression = Expression.Property(parameter, property);
// Convert object type to the actual type of the property
var value = Convert.ChangeType(filter.Value, property.PropertyType, CultureInfo.InvariantCulture);
// Construct equal expression that compares MemberExpression for the property with converted value
var eq = Expression.Equal(memberExpression, Expression.Constant(value));
// Build lambda expresssion (x => x.SampleProperty == some-value)
var lambdaExpression = Expression.Lambda<Func<SampleClass, bool>>(eq, parameter);
// And finally use the expression to filter the collection
query = query.Where(lambdaExpression);
}
var filteredList = query.ToList();
当然,您可以将该代码放在任何类型的泛型方法和过滤器集合中。
对于输入字典,包含两对:"SampleProperty1" - "foo"
和"SampleProperty2" - "bar"
它会产生类似的东西:
listOfSampleClasses
.Where(x => x.SampleProperty1 == "foo")
.Where(x => x.SampleProperty2 == "bar");
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句