I have a method with a signature like this
void RefreshMethod<T>(IEnumerable<T> lst, string propertyName) where T:class
{
Type type = typeof(T);
PropertyInfo property = type.GetProperties().Single(u => u.Name == primaryKeyProperty);
//query goes here
}
Now i want to query that collection for getting all the values whose
propertyName < 0
In a simple scenario it would be as easy as this
lst.where(u=>u.ID<0)
But here i don't have that ID property but have corresponding "PropertyInfo" object.
How should i acheive this.
kindly guide
LINQ to Objects offers usage of any LINQ query supporting IEnumerable for accessing in-memory data collections without any need of LINQ provider (API) as in case of LINQ to SQL or LINQ to XML.
LINQ to Objects does not add any special ability regarding getting and setting property values. But LINQ makes it easy to filter the type members according to various criteria. The following piece of code selects all read/write properties of integer type and converts them to name/value pairs.
Reflection lets us access members of an object, including property getters and setters. Through specialized methods we can read values from properties and write values back into them. LINQ to Objects does not add any special ability regarding getting and setting property values.
Linq to Objects: This provides the ability to query IEnumerable<T> -based information sources which include arrays, collections, list of objects. Linq to XML: This provides efficient, easy-to-use, in-memory XML manipulation capabilities to provide XPath/XQuery functionality to the programming languages using simple query operators.
You can lookup the property-value using property.GetValue(anObjectOfTypeT, null)
.
So something like:
var refreshedList = lst.Where(l => ((int)(property.GetValue(l, null)) < 0).ToList();
This assumes the property will always be of type int though.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With