Search code examples
c#listlinqmerge

LINQ - How to merge two lists and sum specific field when the ids are matched


Considering I have 2 lists (firstList and secondList), both are with the same properties, but with different values.

I need the result for merging both lists, but it must consider the case the field IdALuno match the Id of the secondList and it should sum the values of property Nota.

I`ve seen a couple of examples here nothing that could work in this specific case.

This is my expected result:

  • The idAluno of all lists must appear in the finallist
  • When idAluno matches both lists, it should sum the field Nota
IdALuno Nota
1 9
2 4
3 8
4 2
5 3
6 3

Here is the code:

using System;
using System.Collections.Generic;
using System.Linq;

namespace ConsoleApp1
{
    public class Program
    {
        class Semestre
        {
            public int Nota { get; set; }
            public int IdALuno { get; set; }
        }

        public static void Main()
        {
            List<Semestre> firstList = new List<Semestre>();
            firstList.Add(new Semestre { IdALuno = 1, Nota = 5 });
            firstList.Add(new Semestre { IdALuno = 2, Nota = 4 });
            firstList.Add(new Semestre { IdALuno = 3, Nota = 3 });
            firstList.Add(new Semestre { IdALuno = 5, Nota = 3 });

            List<Semestre> secondList = new List<Semestre>();
            secondList.Add(new Semestre { IdALuno = 1, Nota = 4 });
            secondList.Add(new Semestre { IdALuno = 3, Nota = 5 });
            secondList.Add(new Semestre { IdALuno = 4, Nota = 2 });
            secondList.Add(new Semestre { IdALuno = 6, Nota = 3 });   


            foreach (var item in firstList)
            {
                Console.WriteLine($"idALuno: {item.IdALuno} / Nota: {item.Nota}");
            }
        }
    }

Solution

  • You can use System.Linq to:

    1. Group by IdALuno and sum all Nota.
    2. Order by IdALuno.
    using System.Linq;
    
    List<Semestre> result = new List<Semestre>();
    
    result.AddRange(semestre1);
    result.AddRange(semestre2);
    
    result = result.GroupBy(x => x.IdALuno)
        .Select(x => new Semestre
                {
                    IdALuno = x.Key,
                    Nota = x.Sum(y => y.Nota)
                })
        .OrderBy(x => x.IdALuno)
        .ToList();
    

    Sample program