Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Query a collection using PropertyInfo object in LINQ

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

like image 226
Manvinder Avatar asked Jul 11 '12 11:07

Manvinder


People also ask

What is linlinq to objects?

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.

How to use LINQ to add properties to an object?

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.

What is the difference between reflection and LINQ to objects?

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.

What is the difference between LINQ to objects and to XML?

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.


1 Answers

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.

like image 64
Maarten Avatar answered Oct 19 '22 05:10

Maarten