小编faf*_*ase的帖子

c#迭代列表以合并具有相同字段的项目

所以我会有一个带有匹配字段的数据列表:

class Data
{
   public string type;
   public int amount;
   public Data(string type, int amount)
   {
       this.type = type;
       this.amount = amount;
   }
}


List<Data> list = new List<Data>()
        {
            new Data("A", 20),
            new Data("A", 10),
            new Data("B", 20),
            new Data("B", 20),
            new Data("C", 20)
        };
Run Code Online (Sandbox Code Playgroud)

我希望这些项目合并为一个,如果它们的类型相同,则添加该值。所以我会有“A”=> 30,“B”=> 40 和“C”=> 20。

我可以解决这个问题:

    private IEnumerable<Data> MergeDuplicates(IEnumerable<Data> list)
    {
        Dictionary<string, long> dict = new Dictionary<string, long>();
        foreach(Data data in list) 
        {
            if (dict.ContainsKey(data.type)) 
            {
                dict[data.type] += data.amount;
                continue;
            }
            dict.Add(data.type, data.amount);
        } …
Run Code Online (Sandbox Code Playgroud)

c# linq algorithm

1
推荐指数
2
解决办法
34
查看次数

标签 统计

algorithm ×1

c# ×1

linq ×1