【问题标题】:C# - Remove Key duplicates from KeyValuePair list and add ValueC# - 从 KeyValuePair 列表中删除重复的键并添加值
【发布时间】:2012-11-21 19:07:36
【问题描述】:

我有一个 C# 格式的 KeyValuePair 列表,格式为 string,int,带有示例内容:

mylist[0]=="str1",5
mylist[2]=="str1",8

我想要一些代码来删除其中一项并在另一项中添加重复值。
所以应该是:

mylist[0]=="str1",13

定义代码:

List<KeyValuePair<string, int>> mylist = new List<KeyValuePair<string, int>>();

Thomas,我会尝试用伪代码来解释它。 基本上,我想要

mylist[x]==samestring,someint
mylist[n]==samestring,otherint

成为:

mylist[m]==samestring,someint+otherint

【问题讨论】:

  • 可以添加mylist的定义代码吗?
  • 你真正想做什么?如果您使用伪代码,请尝试更明确。我认为您的示例无法解释您想要做什么。
  • 您需要实际保留订单吗?
  • 看看我的回答,它给了你你想要的东西。

标签: c# list duplicate-removal keyvaluepair


【解决方案1】:
var newList = myList.GroupBy(x => x.Key)
            .Select(g => new KeyValuePair<string, int>(g.Key, g.Sum(x=>x.Value)))
            .ToList();

【讨论】:

    【解决方案2】:
    var mylist = new KeyValuePair<string,int>[2];
    
    mylist[0]=new KeyValuePair<string,int>("str1",5);
    mylist[1]=new KeyValuePair<string,int>("str1",8);
    var output = mylist.GroupBy(x=>x.Key).ToDictionary(x=>x.Key, x=>x.Select(y=>y.Value).Sum());
    

    【讨论】:

      【解决方案3】:

      我会使用不同的结构:

      class Program
      {
          static void Main(string[] args)
          {
              Dictionary<string, List<int>> dict = new Dictionary<string, List<int>>();
              dict.Add("test", new List<int>() { 8, 5 });
              var dict2 = dict.ToDictionary(y => y.Key, y => y.Value.Sum());
              foreach (var i in dict2)
              {
                  Console.WriteLine("Key: {0}, Value: {1}", i.Key, i.Value);
              }
              Console.ReadLine();
          }
      }
      

      第一个字典应该是您的原始结构。要向其中添加元素,首先检查键是否存在,如果存在,只需将元素添加到值列表中,如果不存在,则将新项目添加到字典中。第二个字典只是第一个字典对每个条目的值列表求和的投影。

      【讨论】:

        【解决方案4】:

        非 Linq 答案:

        Dictionary<string, int> temp = new Dictionary<string, int>();
        foreach (KeyValuePair<string, int> item in mylist)
        {
            if (temp.ContainsKey(item.Key))
            {
                temp[item.Key] = temp[item.Key] + item.Value;
            }
            else
            {
                temp.Add(item.Key, item.Value);
            }
        }
        List<KeyValuePair<string, int>> result = new List<KeyValuePair<string, int>>(temp.Count);
        foreach (string key in temp.Keys)
        {
            result.Add(new KeyValuePair<string,int>(key,temp[key]);
        }
        

        【讨论】:

        • 在什么方面比仅仅学习使用 linq 更好。对于这个特定的场景,linq 更具表现力。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-05-17
        • 1970-01-01
        • 2022-08-05
        • 1970-01-01
        • 2022-08-17
        相关资源
        最近更新 更多