how to turn a string into a linq expression?

Viewed 14358

Similar: Convert a string to Linq.Expressions or use a string as Selector?

A similar one of that one: Passing a Linq expression as a string?

Another question with the same answer: How to create dynamic lambda based Linq expression from a string in C#?

Reason for asking something which has so many similar questions:

The accepted answer in those similar questions is unacceptable in that they all reference a library from 4 years ago (granted that it was written by code master Scott Gu) written for an old framework (.net 3.5) , and does not provide anything but a link as an answer.

There is a way to do this in code without including a whole library.

Here is some sample code for this situation:

    public static void getDynamic<T>(int startingId) where T : class
    {
        string classType = typeof(T).ToString();
        string classTypeId = classType + "Id";
        using (var repo = new Repository<T>())
        {
            Build<T>(
             repo.getList(),
             b => b.classTypeId //doesn't compile, this is the heart of the issue
               //How can a string be used in this fashion to access a property in b?
            )
        }
    }

    public void Build<T>(
        List<T> items, 
        Func<T, int> value) where T : class
    {
        var Values = new List<Item>();
        Values = items.Select(f => new Item()
        {
            Id = value(f)
        }).ToList();
    }

    public class Item
    {
     public int Id { get; set; }
    }

Note that this is not looking to turn an entire string into an expression such as

query = "x => x.id == somevalue";

But instead is trying to only use the string as the access

query = x => x.STRING;
3 Answers
Related