Home > Blockchain >  C# Linq map one list with another list in the same order
C# Linq map one list with another list in the same order

Time:10-20

I am very new to LINQ

in Linq below is what I am trying to achieve :

I have two classes - List<ClassA> - List<ClassB>

Now I want to map 1st item of Class A to first item of Class b


    ClassA.ForEach( a => {
    // how to get the items from ClassB in the same order as it is in CLass b and assign it to Class A
    });

CodePudding user response:

i would try something like this:

 List<int> listA = new List<int>();

 List<int> listB = new List<int>();

 listA.Add(1);

 listB.AddRange(listA);

i know it is not LINQ but i think this approach is simpler

CodePudding user response:

 List<int> listA = new List<int>();
 List<int> listB = new List<int>();

 listA = listA.Concat(listB).ToList();

CodePudding user response:

You can Select the item along with its index as follows:

yourList.Select((x, i) => new {element = v, index = i})

Then, you can apply First to join them by index value:

tempList = list2.Select((x, i) => new { somethingElse = x, index = i });
list1.Select((x, i) => new {
    something = x,
    somethingElse => tempList.First((item) => item.index == i) )
});

I do not have a .NET env at hand and I did not work in it for a long while, so if there are typos, let me know.

  • Related