Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq access property by variable

Tags:

c#

linq

where

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);
like image 853
Rafael Herscovici Avatar asked Jan 07 '12 15:01

Rafael Herscovici


3 Answers

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);
like image 174
L.B Avatar answered Nov 16 '22 01:11

L.B


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);
}
like image 4
JaredPar Avatar answered Nov 15 '22 23:11

JaredPar


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.

like image 2
Michiel van Oosterhout Avatar answered Nov 16 '22 00:11

Michiel van Oosterhout