Click here to Skip to main content
15,881,803 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
  var phones = new List<string>
            {
                "samsung",
                "apple",
                "Redmi",
            };

var phones2 = new List<string>
            {
                "apple",
                "samsung"
            };


How I want something like this in LINQ.


SELECT * FROM phones WHERE IN ("apple","samsung");
or
SELECT * FROM phones WHERE IN (select * from phones2 );

What I have tried:

How to achieve this in LINQ.

Method or Query any type is fine.
Posted
Updated 27-Mar-23 2:26am

It is unclear what you are asking. Do you want the Intersection, Union, etc or???

Here is a tutorial that covers these and other filters: LINQ Set Operations (Distinct, Union, Intersect, Except) - Tutlane[^]
 
Share this answer
 

If you want to select only the items that are common to both Lists you can do something along these lines.


C#
var phones = new List<string>
            {
                "samsung",
                "apple",
                "Redmi",
                "Bar"
            };

var phones2 = new List<string>
            {
                "apple",
                "samsung",
                "Foo"
            };
//The Where extension takes a method that has a string as a parameter and returns a bool
var inclusiveList=   phones.Where(phones2.Contains).ToList();
Console.WriteLine(string.Join(',', inclusiveList));
//outputs: samsung,apple
 
Share this answer
 
Comments
Graeme_Grant 27-Mar-23 9:38am    
Why not use Intersect? I would use Where if the two object types were different. Take a look at the link that I provided.
George Swan 27-Mar-23 10:38am    
Because the OP was trying to use Where and I thought it would be helpful to post an example that employed it. You are quite correct Graeme, Intersect is better for larger collections. Regards, George.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900