linq - C# how to filter a list by different properties at runtime -


im pretty new c#/unity forgive me.

im writing filtering system filter list of properties of class @ runtime. im planning on building kind of whereclause filter lists (i know hit server list need, want filter data have)

say have list of class "myclass" 4 properties: "param1".."param4"

if wanted filter param1 , param2 do:

list<myclass> mylist = new list<myclass>(existinglist); mylist = mylist.where(g => g.param1 == somevalue && g.param2 == someothervalue).tolist(); 

how generate same clause @ runtime?

thank you!

you can write extension method this:

public static ienumerable<t> where<t>(this ienumerable<t> source, string propname, object value) {     var type = typeof(t);      var propinfo = type.getproperty(propname,bindingflags.ignorecase | bindingflags.public | bindingflags.instance);      var parameterexpr = expression.parameter( type, "x" ); //x     var memberaccessexpr = expression.makememberaccess( parameterexpr, propinfo ); //x.prop      var lambda = expression.lambda( expression.equal(memberaccessexpr, expression.constant(value)),                                      parameterexpr );         //x=>x.prop==value      var mi = typeof(enumerable)                 .getmethods()                 .where(m => m.name == "where")                 .first(m => m.getparameters().count() == 2)                 .makegenericmethod(type);      return (ienumerable<t>)mi.invoke(null, new object[] { source, lambda.compile() }); } 

you can use as

var test = new[] { new { = 1 }, new { = 2 } }.where("a", 1).tolist(); 

Comments

Popular posts from this blog

java - nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet Hibernate+SpringMVC -

sql - Postgresql tables exists, but getting "relation does not exist" when querying -

asp.net mvc - breakpoint on javascript in CSHTML? -