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

后端 未结 4 1852
长发绾君心
长发绾君心 2020-12-09 01:24

Can I declare / use some variable in LINQ?

For example, can I write following LINQ clearer?

var q = from PropertyDescriptor t in TypeDescriptor.GetPr         


        
4条回答
  •  执笔经年
    2020-12-09 01:46

    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);
    

提交回复
热议问题