Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to compare multiple values in a linq expression to a generic list?

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);
like image 724
Rayshawn Avatar asked Mar 14 '13 15:03

Rayshawn


People also ask

What does Distinct do in LINQ?

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

What does => mean in LINQ?

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.

Is LINQ good for performance?

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

What is the advantage of LINQ in C#?

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.


1 Answers

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));
like image 87
JaredPar Avatar answered Oct 12 '22 14:10

JaredPar