Arya
Arya

Reputation: 91

Select similar items of different lists using using C# and Linq

In an asp.net mvc application, I am trying to perform a selection based on what user selects from product specifications. Imagine a user selected these parameters as a selection:

manufacturer: [apple, sony, samsung]
ram: [8, 128, 256]
size: [12, 13.5]

based on that, lets say the selection resulted in lists of product Ids.

list1={10,12,18,100}
list2={10,18,20,21,100,102}
list3={1,2,9,10,12,18,100}

the result should be common Ids:

result={10,18,100}

Since there might be more than 3 lists, is there a Linq command for any number of lists?

Upvotes: 1

Views: 68

Answers (2)

lakshmi vishkarma
lakshmi vishkarma

Reputation: 21

Use intersect to get similar item from Two Lists.

List<string> Fruits = new List<string>();
        Fruits.Add("Apple");
        Fruits.Add("Mango");
        Fruits.Add("Grapes");
        Fruits.Add("Banana");
        Fruits.Add("Orange");
        Fruits.Add("Sweet Potato");

        List<string> Vegetables = new List<string>();
        Vegetables.Add("Tomato");
        Vegetables.Add("Potato");
        Vegetables.Add("Onion");
        Vegetables.Add("Apple");
        Vegetables.Add("Orange");
        Vegetables.Add("Banana");

        var Data = Fruits.Intersect(Vegetables).ToList();
        foreach(var d in Data)
        {
            Console.WriteLine(d);
        }

Output:- Apple Banana Orange

Upvotes: 2

Manuel Fabbri
Manuel Fabbri

Reputation: 568

You can use the Intersect method provided by .NET. Here's the documentation about the usage

Upvotes: 5

Related Questions