Search code examples
c#.netlinq

Indices of the matched list items in LINQ query


I need to know the indices of the matched items in the LINQ query. I get an error in join when I try to get index. My code is as below and I am expecting (2, 0) for the first match and (3, 1) for the second match. I am new to LINQ and suggestions welcome.

public class Test
{
    public int a;
    public string b;

    public Test(int x, string y) { a = x; b = y; }
}        


    List<Test> a1= new List<Test>();  
    List<Test> b1= new List<Test>();  

    a1.Add(new Test(1, "test1-a"));
    a1.Add(new Test(2, "test2-a"));
    a1.Add(new Test(3, "test3-a"));
    a1.Add(new Test(4, "test4-a"));

    b1.Add(new Test(3, "test3-b"));
    b1.Add(new Test(4, "test4-b"));
    b1.Add(new Test(5, "test5-b"));
    b1.Add(new Test(6, "test6-b"));

    var x = from m in a1
            join n in b1 
            on m.a equals n.a
            select((index) => new { index, n.b });

Solution

  • You can use the overload of the Select method that also provides the index. But you need to do this before joining the collections. So it should look like this :

        var x =
                from m in a1.Select((r, ix) => new {Ix = ix, T = r})
                join n in b1.Select((r, ix) => new {Ix = ix, T = r}) 
                 on m.T.a equals n.T.a
                select (m.Ix, n.Ix);
    

    Fiddle