Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

linq

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?

like image 852
cnd Avatar asked Aug 05 '13 11:08

cnd


People also ask

What is LINQ Why should we use LINQ and what are the benefits of using LINQ?

LINQ offers the following advantages: LINQ offers a common syntax for querying any type of data sources. Secondly, it binds the gap between relational and object-oriented approachs. LINQ expedites development time by catching errors at compile time and includes IntelliSense & Debugging support.

What kind of data can be queried with LINQ?

LINQ offers common syntax for querying any type of data source; for example, you can query an XML document in the same way as you query a SQL database, an ADO.NET dataset, an in-memory collection, or any other remote or local data source that you have chosen to connect to and access by using LINQ.

Is LINQ inefficient?

Conclusion. It would seem the performance of LINQ is similar to more basic constructs in C#, except for that notable case where Count was significantly slower. If performance is important it's crucial to do benchmarks on your application rather than relying on anecdotes (including this one).


3 Answers

var q = from PropertyDescriptor t in TypeDescriptor.GetProperties(instance)
        let u = t.ComponentType.GetProperty(t.Name)
        where (u != null)
        select u;
like image 41
King King Avatar answered Oct 11 '22 09:10

King King


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);
like image 162
It'sNotALie. Avatar answered Oct 11 '22 09:10

It'sNotALie.


Yes, using the let keyword:

var q = from PropertyDescriptor t in TypeDescriptor.GetProperties(instance)
    let nameProperty = t.ComponentType.GetProperty(t.Name)
    where (nameProperty != null)
    select nameProperty;
like image 40
Matten Avatar answered Oct 11 '22 11:10

Matten