计算KeyValuePair中的值总和 [英] Calculate Sum of values in KeyValuePair

查看:72
本文介绍了计算KeyValuePair中的值总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


我团队的KeyValuePair具有以下值
         私有静态List< KeyValuePair< string,int>> d = new List< KeyValuePair< string,int>>>();


I team i have KeyValuePair with below values
           private static List<KeyValuePair<string, int>> d = new List<KeyValuePair<string, int>>();

       静态void Main(string [] args)
        {
            d.Add(new KeyValuePair< string,int>("joe",100));
            d.Add(new KeyValuePair< string,int>("joe",200));
            d.Add(new KeyValuePair< string,int>("jim",100));
            var result = d.Where(x => x.Key =="joe");
                                       foreach(结果为var q)
                                    Console.WriteLine(q.Value  );
                                       Console.ReadLine();
        }

         static void Main(string[] args)
         {
              d.Add(new KeyValuePair<string, int>("joe", 100));
              d.Add(new KeyValuePair<string, int>("joe", 200));
              d.Add(new KeyValuePair<string, int>("jim", 100));
              var result = d.Where(x => x.Key == "joe");
             foreach(var q in result)
                 Console.WriteLine(q.Value   );
             Console.ReadLine();
         }

何时我将上述keyvaluepair传递为输入,它应该返回另一个resut键值对(例如
)中的项的总和 乔300
吉姆100

when  i pass above keyvaluepair as input, it should return a sum of items items in another resut key value pair like
joe, 300
jim,100

有帮助吗?

推荐答案

问候安尼尔.

KeyValuePairs实际上并不是要以这种方式使用.使用Tuple或您自己的定制类会更好.

KeyValuePairs really are not meant to be used in this way. You would be better off using a Tuple or your own custom-made class.

但是,如果您坚持使用KeyValuePairs,这是一种可行的方法.

But if you insist on using KeyValuePairs, here is one way that might work.

      static void Main(string[] args)
      {
         d.Add(new KeyValuePair<string, int>("joe", 100));
         d.Add(new KeyValuePair<string, int>("joe", 200));
         d.Add(new KeyValuePair<string, int>("jim", 100));

         List<KeyValuePair<string, int>> sums = new List<KeyValuePair<string, int>>();
         foreach(KeyValuePair<string, int> pair in d)
         {
            if(sums.FindIndex(x => x.Key == pair.Key) < 0)
            {
               int total = d.Where(x => x.Key == pair.Key).Sum(x => x.Value);
               sums.Add(new KeyValuePair<string, int>(pair.Key, total));
            }
         }

         foreach (var q in sums)
            Console.WriteLine("{0} {1}", q.Key, q.Value);
         Console.ReadLine();
      }


这篇关于计算KeyValuePair中的值总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆