[C# Lambda] 依資料Group某欄位數量
C# lamba List<object>, 其中object class有4個欄位, 分別為A,B,C,D, 其中A,B,C為string, D為int, 如何將A,B,C為條件進行Group by取得加總D的結果
class Program
{
static void Main()
{
List<MyObject> objects = new List<MyObject>
{
new MyObject { A = "A1", B = "B1", C = "C1", D = 10 },
new MyObject { A = "A1", B = "B1", C = "C2", D = 20 },
new MyObject { A = "A2", B = "B2", C = "C1", D = 30 },
new MyObject { A = "A2", B = "B2", C = "C2", D = 40 },
new MyObject { A = "A2", B = "B3", C = "C3", D = 50 }
};
var groupedObjects = objects
.GroupBy(obj => new { obj.A, obj.B, obj.C })
.Select(group => new
{
group.Key.A,
group.Key.B,
group.Key.C,
SumD = group.Sum(obj => obj.D)
});
foreach (var group in groupedObjects)
{
Console.WriteLine($"A: {group.A}, B: {group.B}, C: {group.C}, SumD: {group.SumD}");
}
}
}
class MyObject
{
public string A { get; set; }
public string B { get; set; }
public string C { get; set; }
public int D { get; set; }
}
留言
張貼留言