【问题标题】:C# Extension method to filter listC# 过滤列表的扩展方法
【发布时间】:2013-03-26 01:56:42
【问题描述】:

我找到了以下过滤列表的扩展方法。我对此很陌生,因此我想检查是否有人可以帮助我。此方法比较精确值,但我想使用包含而不是精确比较。有什么想法

    public static IEnumerable<T> FilterByProperty<T>(this IEnumerable<T> source,string property,object value)
    {
        var propertyInfo = typeof(T).GetProperty(property);
        return source.Where(p => propertyInfo.GetValue(p, null) == value);
    }

【问题讨论】:

  • 为什么不直接使用Where 子句? list.Where(c =&gt; c.MyProperty == "someValue");
  • MyProperty 已修复,我想让它动态化..
  • 我认为你不能假设 Contains 是为 Object 定义的 :)

标签: linq c#-4.0 extension-methods


【解决方案1】:

如果要将等于 == 更改为 Contains。试试这个:

public static IEnumerable<T> FilterByProperty<T>(this IEnumerable<T> source,string property,object value)
    {
        var propertyInfo = typeof(T).GetProperty(property);
        return source.Where(p => propertyInfo
                                      .GetValue(p, null)
                                      .ToString() //be aware that this might be null
                                      .Contains(value));
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-05-31
    • 1970-01-01
    • 2021-12-31
    • 1970-01-01
    • 2010-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多