請教各位大大,
請問有什麼辦法寫法可以合併這兩個List item,
不用foreach或者for,
並且如果有重複的name並且不為0 就更新他的amount。
List<Wallet> list_A = new List<Wallet>(){
new Wallet(){ name = "A" , amount = 0},
new Wallet(){ name = "B" , amount = 0},
new Wallet(){ name = "C" , amount = 0}
};
List<Wallet> list_B = new List<Wallet>(){
new Wallet(){ name = "A" , amount = 10}
};
public class Wallet
{
public string name { get; set; }
public decimal amount { get; set; }
}
邏輯
1.因為是兩個集合綜合比較,所以使用union
2.並且如果有重複的name並且不為0 就更新他的amount。
假如list_A amount 是 20,list_B amount是10情況下該如何選擇呢?
所以我這邊取其最大值為準,所以使用group by name + max(amount)
Code
void Main()
{
List<Wallet> list_A = new List<Wallet>(){
new Wallet(){ name = "A" , amount = 0},
new Wallet(){ name = "B" , amount = 0},
new Wallet(){ name = "C" , amount = 0}
};
List<Wallet> list_B = new List<Wallet>(){
new Wallet(){ name = "A" , amount = 10}
};
var result = list_A.Union(list_B).GroupBy(g => g.name).Select(s => new Wallet() {name=s.Key,amount=s.Max(m=>m.amount)}).ToList();
}
public class Wallet
{
public string name { get; set; }
public decimal amount { get; set; }
}
結果:
name amount
A 10
B 0
C 0