0

## C# 合併兩個集合列表

Ks 2019-02-21 10:23:15672 瀏覽

``````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 個回答

4

iT邦大師 1 級 ‧ 2019-02-21 10:35:27

1.因為是兩個集合綜合比較,所以使用`union`

2.`並且如果有重複的name並且不為0 就更新他的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
``````

Ks iT邦新手 4 級 ‧ 2019-02-21 10:44:09 檢舉

Ks iT邦新手 4 級 ‧ 2019-02-22 15:48:01 檢舉