I have a complex entity object I am querying that has values that need to be compared to a generic list in order to select the correct objects. I am trying to find a way to compare the Id values in the the entity object to all the values in my list without having to put the query inside a loop.
This is what I have:
Generic List:
List<int> input = new List<int>()
{
3,4,5....
};
My Query-Does not work:
ManagerToGetRepo mgr = new ManagerToGetRepo();
var result = mgr.GetAllData()
.Where(a=>a.someObject.anotherObj.Id == input.Values);
C# Linq Distinct() method removes the duplicate elements from a sequence (list) and returns the distinct elements from a single data source. It comes under the Set operators' category in LINQ query operators, and the method works the same way as the DISTINCT directive in Structured Query Language (SQL).
The => operator can be used in two ways in C#: As the lambda operator in a lambda expression, it separates the input variables from the lambda body. In an expression body definition, it separates a member name from the member implementation.
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).
Advantages of Using LINQ 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 expressions are Strongly Typed.
Just use the List<T>.Contains
method to see if each value is in the collection
var result = mgr.GetAllData()
.Where(a => input.Contains(a.someObject.anotherObj.Id));
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