Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merging few lists into one using linq

Tags:

c#

merge

list

linq

Is there a simple way to take few lists of the same size and create a new one ouf of their min/max values in each index with linq? I mean how to compare items at same index and pick which one is Max or Min like here:

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

for(int i=0; i< 5; i++)
{
    int CurrentHighest=0;
    for(int j=0; j<2; j++)
    {
        if (Some2dList[j][i] > CurrentHighest)
            CurrentHighest = Some2dList[j][i];
    }
    NewList.Add(CurrentHighest);
}
//Which gives me {5,4,3,4,5}

I've simplified those loops to look clearlier. I know I could use Concat and GroupBy, and then select Max out of each, but for simple types and classes without a key value I can't figure it out.

edit: I shoul've been more precise. List in example are assigned manually, but I'm asking about solution, that would be flexible for ANY amount of lists compared. Also, lists are always same sized.

like image 515
Tarec Avatar asked Dec 07 '25 03:12

Tarec


2 Answers

No limit on the size of List Of Lists and lists can be any length.

List<List<int>> Some2dList = new List<List<int>>{ 
        new List<int> { 1, 2, 3, 4, 5 }, 
        new List<int> { 5, 4, 3, 2, 1 },
        new List<int> { 8, 9 } 
        };
var res = Some2dList.Select(list => list.Select((i, inx) => new { i, inx }))
            .SelectMany(x => x)
            .GroupBy(x => x.inx)
            .Select(g => g.Max(y=>y.i))
            .ToList();
like image 81
I4V Avatar answered Dec 08 '25 16:12

I4V


This should do what you are looking for:

List<int> newList = Some2dList[0].Select((x, column) => Math.Max(x, Some2dList[1][column])).ToList();

The trick is taking the overload of Select that allows you to have the index of the item you are working with in the lambra expression : this makes possible compare two items in the two different lists placedat the same index. Obviously if it's the min you are looking for, use Math.Min instead of Math.Max.

Just one thing, I take for granted that the two sublists have the same number of elements.

like image 28
Save Avatar answered Dec 08 '25 16:12

Save



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!