Let's say I have a class like:
public class Foo
{
public string Title {get;set;}
}
Now, let's assume I have a public List<Foo> myList
which I want to filter by Linq as so:
var x = myList.Where(f => f.Title == myValue);
Everything is nice and clear until now.
But how can access the property by variable? Something like:
string myProperty = "Title";
var x = myList.Where(f => f.myProperty == myValue);
You can write an extension method
public static class MyExtensions
{
public static object GetProperty<T>(this T obj, string name) where T : class
{
Type t = typeof(T);
return t.GetProperty(name).GetValue(obj, null);
}
}
and use it like this
var x = myList.Where(f => f.GetProperty("Title") == myValue);
This is not the type of situation that LINQ is used for. LINQ is a fluent interface for manipulating collections. Accessing members via a textual representation is done with reflection.
object GetProperty(Foo f, string propertyName) {
var type = typeof(Foo);
var propInfo = type.GetProperty(propertyName);
return propInfo.GetValue(f, null);
}
If you need to compose your queries dynamically on the fly, you can use the LINQ Dynamic Query library, a sample from Microsoft:
This sample shows a technique for composing LINQ statements on the fly, dynamically, at run time.
Reference the library in your code:
using System.Linq.Dynamic;
Your query would look like this:
// You can use a string as the argument for the Where method
// meaning you can compose this string dynamically
string myProperty = "Title";
var x = myList.Where(myProperty + " = " + myValue);
It's also possible to use placeholder in the query string, which improves readability (somewhat):
var x = myList.Where("@0 = @1", myProperty, myValue);
See also this post from Scott Guthrie: Dynamic LINQ Part 1: Using the LINQ Dynamic Query Library (I don't think there ever was a part 2...)
Note: you have to compile the sample code from Microsoft and reference the built assembly, or you could include the code in your own project.
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