How to query collection of type T, to return all items of T, where any of T's properties contains some string?
EDIT:
Assume that I convert each property to string before check if contains.
How to query collection of type T, to return all items of T, where any of T's properties contains some string?
EDIT:
Assume that I convert each property to string before check if contains.
You mean something like this ?
list.Any(x => x.GetType()
.GetProperties()
.Any(p =>
{
var value = p.GetValue(x);
return value != null && value.ToString().Contains("some string");
}));
This could be more efficient if you get the type and the properties only once:
var type = list.GetType().GetGenericArguments()[0];
var properties = type.GetProperties();
var result = list.Any(x => properties
.Any(p =>
{
var value = p.GetValue(x);
return value != null && value.ToString().Contains("some string");
}));
Note: if you want to check whether or not any of the properties contains some string, use Any
, if you want also get the items that matches with your criteria use Where
method instead of first Any
. Use list.Where(x => properties.Any(...));
you can use reflection (this version is not efficient, but you've got the idea).
myList.Where(m => m.GetType().GetProperties().Any(x => x.GetValue(m, null) != null && x.GetValue(m, null).ToString().Contains("someString"));