考慮到我有 2 個串列(firstList 和 secondList),它們都具有相同的屬性,但具有不同的值。
我需要結果合并兩個串列,但它必須考慮第二個串列的欄位 IdALuno 匹配 de Id 的情況,它應該對屬性 Nota 的值求和。
我在這里似乎有幾個例子,在這種特定情況下沒有任何作用。
這是我的預期結果:
- 所有名單的idAluno必須出現在決賽名單中;
- 當 idAluno 匹配兩個串列時,它應該對欄位 Nota 求和;
伊達盧諾 | 諾塔
1 | 9
2 | 4
3 | 8
4 | 2
5 | 3
6 | 3
這是代碼:
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}");
}
}
}
uj5u.com熱心網友回復:
您可以System.Linq用來:
- 分組
IdALuno和總和Nota。 - 訂購
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();
示例程式
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/471240.html
