Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Linq Find all indexes of item in List<int> within another List<int>

Tags:

c#

list

linq

I have a List looks like:

List<int> List1= new List<int>(){3,4,5};

and another looks like:

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

How can I use Linq to get an array of all of the indices of List1 from List2 like below:

var ResultList = {2,3,4};
like image 976
Karaiden Avatar asked Dec 07 '22 16:12

Karaiden


2 Answers

var ResultList = List1.Select(x => List2.IndexOf(x));
like image 52
caesay Avatar answered Dec 10 '22 06:12

caesay


This is a longer solution but prevents a nested loop through the array which may be faster if the arrays are huge (but slower if the arrays are small).

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

var lookup = new Dictionary<int, int>();
for(var i=0; i<List2.Count; i++) {
    lookup[List2[i]] = i;
}

List<int> Result = List1.Select(i => {
    int index;
    return lookup.TryGetValue(i, out index) ? index : -1;
}).ToList();
like image 41
Samuel Neff Avatar answered Dec 10 '22 06:12

Samuel Neff