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?
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.
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.
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).
var q = from PropertyDescriptor t in TypeDescriptor.GetProperties(instance)
let u = t.ComponentType.GetProperty(t.Name)
where (u != null)
select u;
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);
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With