Search code examples
c#listindexingreturn

C# Return ints from a list and create a list of tuples with each int and the index each int had in the first list


I have a list of int and I find items within the list with FindAll and return the results in another list. Since the second list has fewer elements, the index of the elements may be different from those of the first list. So, I would like to have a simple and fast system to have the results of the FindAll linked somewhat to the index they had in the first list. I think a List of tuples with two int would be ideal as the first int of the tuple will be each of the int of the second list, while the second int of the tuple will be the index each item of the second list had in the first list. I would like the tuples to be the original tuples (not ValueTuple)

List<int> list1 = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8 };
List<int> list2 = new List<int>();
List<Tuple<int, int>> list2index = new List<Tuple<int, int>>();


list2 = list1.FindAll(x => x > 3 && x < 7);  // Returns 4 5 6

/*
Now I want to create the list of tuples<int, int> so it should 
return: 

(4, 3)  
(5, 4)
(6, 5)

The first int is the first item of the list2 
and the second int is its index in the list1

How can I create this list of tuples in a fast way?          
*/

Solution

  • I would rather suggest you use a for loop instead of linq for performance:

        for (int i = 0; i < list1.Count; i++)
        {
            int x = list1[i];
            if (x > 3 && x < 7)
                list2index.Add(new Tuple<int, int>(x,i));
        }