score:10
you can build a lambda expression to create a proper predicate using the expression
class.
public static expression<func<tinput, bool>> createfilterexpression<tinput>(
ienumerable<filter> filters)
{
parameterexpression param = expression.parameter(typeof(tinput), "");
expression lambdabody = null;
if (filters != null)
{
foreach (filter filter in filters)
{
expression compareexpression = expression.equal(
expression.property(param, filter.fieldname),
expression.constant(filter.filterstring));
if (lambdabody == null)
lambdabody = compareexpression;
else
lambdabody = expression.or(lambdabody, compareexpression);
}
}
if (lambdabody == null)
return expression.lambda<func<tinput, bool>>(expression.constant(false));
else
return expression.lambda<func<tinput, bool>>(lambdabody, param);
}
with this helper method, you can create an extension method on any iqueryable<t>
class, so this should work for every linq backend:
public static iqueryable<t> where<t>(this iqueryable<t> source,
ienumerable<filter> filters)
{
return queryable.where(source, createfilterexpression<t>(filters));
}
...which you can call like this:
var query = context.persons.where(userfilters);
if you want to support ienumerable<t>
collections as well, you'll need to use this extra extension method:
public static ienumerable<t> where<t>(this ienumerable<t> source,
ienumerable<filter> filters)
{
return enumerable.where(source, createfilterexpression<t>(filters).compile());
}
note that this only works for string properties. if you want to filter on fields, you'll need to change expression.property
into expression.field
(or makememberaccess
), and if you need to support other types than string properties, you'll have to provide more type information to the expression.constant
part of the createfilterexpression
method.
score:0
i would add a method to the filter
class to check if the filter is satisfied:
class filter
{
public string fieldname {get;set;}
public string filterstring {get;set;}
public bool issatisfied(object o)
{ return o.gettype().getproperty(fieldname).getvalue(o, null) as string == filterstring;
}
you can then use it like this:
var filtered_list = personslist.where(p => userfilters.any(f => f.issatisfied(p)));
score:2
can't you just do
personlist.where(x => x.personname == "yournamehere").tolist() ?
score:3
you can do it via reflection:
iqueryable<person> filteredpersons = personslist.asqueryable();
type persontype = typeof(person);
foreach(filter filter in userfilters) {
filteredpersons = filteredpersons.where(p => (string)persontype.invokemember(filter.fieldname, bindingflags.getproperty, null, p, null) == filter.filterstring);
}
(not compiled, but this should be along the right track)
Source: stackoverflow.com
Related Query
- Filtering collection with LINQ
- Filtering a collection with Linq and multiple criteria
- Find a certain value from a source collection in a target collection of different type with linq
- Problem with filtering data by prefix and return collection of proper data with LINQ
- Dynamic linq expression for filtering with enum collection
- Paging a collection with LINQ
- Linq to update a collection with values from another collection?
- Sorting an observable collection with linq
- query a sub-collection of a collection with linq
- linq how to select a parent with a child collection that contains one or many of an array (or list) of values
- LINQ sum collection of items to return object with results (multiple columns)
- How can I iterate over a collection and change values with LINQ extension methods?
- Filter a collection with LINQ vs CollectionView
- C# Linq - get objects with not empty collection
- LINQ WHERE method alters source collection
- Using LINQ to generate a random size collection filled with random numbers
- Check if a value is in a collection with LINQ
- How do I convert IEnumerable to Collection with linq
- Linq with custom base collection
- Best way to use LINQ to Entities with a Collection Property
- Change item in collection with LINQ
- Sum a collection of objects which contain numeric properties only with LINQ
- Can I use a collection initializer with LINQ to return a fully populated collection?
- A LINQ query with grouping and filtering of special groups
- LINQ Source Code Available
- Filtering a nested collection using linq
- Update property in object collection with linq
- LINQ Sum Nested collection with GroupBy and OrderByDescending
- LINQ Union between two tables with the same fields and then returned in a collection
- Distinct Linq filtering with additional criteria
More Query from same tag
- SQL RANDOM ORDER BY ON JOINED TABLE
- How to compare the dates and gets the day count using c# in LINQ
- Where returns wrong record
- Where with IN operator using Linq on NHibernate
- How to convert LINQ nested Selectmany to SQL Regular Statements
- Sort list of objects by varying parameter
- Select Dictionary's List with linq
- Use method in entity framework query
- Randomize but exclude the random variable
- Group By 'MM-dd-yyyy hh-mm'
- Generic method with dynamically selected parameter in predicate
- Return the result of joining two tables in Silverlight 4.0
- Linq to sql, unable to separate query
- How to compare difference between two datatable of same format?
- Linq Table to DataTable casting
- Get rating for products and product category
- LINQ to SQL in Visual Studio 2005
- LINQ RemoveAll where property isn't working
- how to `.Take()` on a string and get a string at the end?
- Parent and collection of child objects
- How to create an UnaryExpression on Math functions as Log, Cos, Sin
- How to get ONLY unique values from list C#
- Return List with Maximum Count using Linq
- How do I merge two LINQ statements into one to perform a list2.Except(list1)?
- Access Navigation Property of type ICollection
- Select distinct values from a list using LINQ in C#
- Use DataSet for retrieving, updating and inserting data to SQLite
- Filter based on a string value in List<string> column in a table Entity Framework Core
- List Distinct is not working in LINQ instead of GroupBy
- Entity Framework GroupBy take the oldest with mySQL