mistake22
mistake22

Reputation: 93

How to select several specific elements in LINQ?

I have a list of integers as mentioned below.

List<int> numbers=new List<int>(){1,2,3,4,5,6};

and I would like to select numbers, that are in an array of integers:

int[] somenumbers=new int[]{1,3,5};

how can I do this with LINQ?

Upvotes: 2

Views: 68

Answers (2)

Cid
Cid

Reputation: 15247

You can use Intersect() to get the common elements between 2 IEnumerable<T>s :

List<int> numbers=new List<int>(){1,2,3,4,5,6};
int[] somenumbers=new int[]{1,3,5, 42};
    
var commonNumbers = numbers.Intersect(somenumbers);
Console.WriteLine(string.Join(", ", commonNumbers)); // 1, 3, 5

Note that the order of the collections to compare doesn't matter :

commonNumbers = somenumbers.Intersect(numbers);
Console.WriteLine(string.Join(", ", commonNumbers)); // 1, 3, 5

Try it yourself

Upvotes: 1

Amit Verma
Amit Verma

Reputation: 2490

Try this

List<int> numbers = new List<int>() { 1, 2, 3, 4, 5, 6 };
int[] somenumbers = new int[] { 1, 3, 5 };
var result = numbers.Where(x => somenumbers.Contains(x));

Upvotes: 2

Related Questions