Dilshod
Dilshod

Reputation: 3311

Using variables in the lambda

I am using Linq to filter some things and some times I need to use reflection to get the value. Here is the example:

//...
PropertyType[] properties = myType.GetProperties();
var filtered = properties.Where(p=>p.PropertyType==typeof(MyMetaData) 
&& ((MyType)p.GetValue(obj)).Name=="name"
&& ((MyType)p.GetValue(obj)).Length==10
).ToList();
//...

In my example I am using GetValue() method more than one time. Is there way if I can use variable to store it? I think that will help with performance.

Upvotes: 1

Views: 89

Answers (2)

King King
King King

Reputation: 63317

It looks like that to include some variable in a LINQ we have to use the expression query, not method query, like this:

var filtered = (from x in properties
               let a = (x.PropertyType is MyType) ? (MyType) x.GetValue(obj) : null
               where a != null && a.Name == "name" && a.Length == 10).ToList();

I think this also works for method query with some Select:

var filtered = properties.Select(p=> new {p, a = (p.PropertyType is MyType) ? (MyType) p.GetValue(obj) : null})
                         .Where(x=>x.a != null && x.a.Name == "name" && x.a.Length == 10)
                         .Select(x=>x.p).ToList();

Upvotes: 7

Habib
Habib

Reputation: 223187

Something like following should work with method expression(lambda syntax)

    var filtered = properties.Where(p => 
        {
            if(!p.PropertyType is MyMetaData)
            {
                return false;
            }
            var item = (MyType) p.GetValue(obj);
            return item.Name == "name"
                && item.Length == 10
        }
    ).ToList();

Upvotes: 5

Related Questions