C#, LINQ, 利用group new 來取得多欄位group by
C#, LINQ, 利用group new 來取得多欄位group by
void Main()
{
// 建立 ClassA 的 List
List<ClassA> classAList = new List<ClassA>
{
new ClassA("A1", 10),
new ClassA("A2", 20),
new ClassA("A3", 30),
new ClassA("A1", 15),
new ClassA("A2", 25),
new ClassA("A3", 35)
};
// 建立 ClassB 的 List
List<ClassB> classBList = new List<ClassB>
{
new ClassB("A1", "C1"),
new ClassB("A2", "C2")
};
//classAList.Dump();
//classBList.Dump();
// 使用 LINQ 進行關聯和分組
var query = from a in classAList
join b in classBList on a.A equals b.A
select a;
query.Dump();
var query2 = from a in query
group new { a.A, a.B } by a.A into grouped
select new { A = grouped.Key, SumB = grouped.Sum(item => item.B) };
query2.Dump();
}
// Define other methods and classes here
// ClassA 定義
class ClassA
{
public string A { get; set; }
public int B { get; set; }
public ClassA(string a, int b)
{
A = a;
B = b;
}
}
// ClassB 定義
class ClassB
{
public string A { get; set; }
public string C { get; set; }
public ClassB(string a, string c)
{
A = a;
C = c;
}
}
執行結果 :
A B
A1 10
A2 20
A1 15
A2 25
A SumB
A1 25
A2 45
留言
張貼留言