Can I declare / use some variable in LINQ? Or can I write following LINQ clearer?

Can I declare / use some variable in LINQ?

For example, can I write following LINQ clearer?

var q = from PropertyDescriptor t in TypeDescriptor.GetProperties(instance)
        where (t.ComponentType.GetProperty(t.Name) != null)
        select t.ComponentType.GetProperty(t.Name);

Are there ways to not write / call t.ComponentType.GetProperty(t.Name) two times here?


Solution 1:

You need let:

var q = from PropertyDescriptor t in TypeDescriptor.GetProperties(instance)
        let name = t.ComponentType.GetProperty(t.Name)
        where (name != null)
        select name;

If you wanted to do it in query syntax, you could do it in a more efficient (afaik) and cleaner way:

var q = TypeDescriptor
            .GetProperties(instance)
            .Select(t => t.ComponentType.GetProperty(t.Name))
            .Where(name => name != null);

Solution 2:

var q = from PropertyDescriptor t in TypeDescriptor.GetProperties(instance)
        let u = t.ComponentType.GetProperty(t.Name)
        where (u != null)
        select u;