Tarec
Tarec

Reputation: 3255

Merging few lists into one using 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.

Upvotes: 3

Views: 424

Answers (3)

I4V
I4V

Reputation: 35353

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();

Upvotes: 6

Save
Save

Reputation: 11928

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.

Upvotes: 4

Sayse
Sayse

Reputation: 43300

Little bit abnormal but seems to work. It assumes there is one list though

Enumerable.Range(0, Some2dList.FirstOrDefault().Count)
   .Select(columnIndex => 
       Some2dList.Max(row => row[columnIndex]))
   .ToList();

Upvotes: 3

Related Questions