Home > Mobile >  How to merge two lists using LINQ Suming a especific field when the id matched
How to merge two lists using LINQ Suming a especific field when the id matched

Time:05-06

Considering I have 2 list (firstList and secondList), both with same properties, but with diffent values.

I need the result merge both lists, but it must consider the case the field IdALuno match de Id of the second List it should sum the values of property Nota.

I`ve seem a couple exemples here nothing that could work in this specific case.

This is my expected result:

  • the idAluno of all list must apear in the finallist;
  • When idAluno matches both list, it shoud 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}");
            }
        }
    }

CodePudding user response:

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

  • Related