2013-04-04 65 views
0

我發現下面的擴展方法過濾列表。我對此很新,因此我想檢查是否有人可以幫助我。此方法比較確切的值,但我想使用包含而不是精確比較。任何想法C#擴展方法過濾列表

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); 
    } 
+0

爲什麼不只是使用'Where'子句? 'list.Where(c => c.MyProperty ==「someValue」);' – 2013-04-04 06:15:19

+0

MyProperty已修復,我想讓它動態變化.. – 2013-04-04 06:20:48

+0

我不認爲你可以假設'Contains'是爲'Object' :) – MarcinJuraszek 2013-04-04 06:56:18

回答

0

如果你想==改變等號成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)); 
    }