如何汇总列表< double>与字典中相同的索引 [英] How to sum list<double> of the same index with in the dictionary

查看:98
本文介绍了如何汇总列表< double>与字典中相同的索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嗨朋友,



我的字典有以下结构

Hi Friends,

I have dictionary with below structure

Dictionary<int, List<double>> dicendingvalue = new Dictionary<int, List<double>>();





我需要汇总所有列表< double>> 在相同索引的字典中输入值并需要获得最终结果。



例如

dic key:1,values :{2,3,5}

键:2,值:{5,8,4}



结果{7,11 ,9}



I need to sum all the List<double>> values with in the dictionary of the same index and need to get final result.

for Example
dic key: 1 , values: { 2, 3, 5 }
key: 2 , values: { 5, 8, 4 }

Result {7,11,9}

推荐答案

说实话,我不会使用Linq - 它真的不会很有效率,因为你必须三次打电话给Sum ,这意味着现实中有三个循环。

你可以滥用聚合:

To be honest, I wouldn't use Linq - it really wouldn't be very efficient, as you'd have to call Sum three times, which means three loops in reality.
You could abuse Aggregate:
Dictionary<int, List<double>> dicendingvalue = new Dictionary<int, List<double>>();
dicendingvalue.Add(0, new List<double>() { 0, 0, 0 });
dicendingvalue.Add(1, new List<double>() { 2, 3, 5 });
dicendingvalue.Add(2, new List<double>() { 5, 8, 4 });
var x = dicendingvalue.Values.Aggregate((a, b) => { a[0] += b[0]; a[1] += b[1]; a[2] += b[2]; return a; });

哪会覆盖第一个条目总计,但只需要一次通过。

虽然不完全可读!



我?我使用 foreach ...

Which will overwrite the first entry with the totals, but requires only one pass.
Not exactly readable though!

Me? I'd use a foreach...


提供每个字典的计数值应该相同。



试试这个。

Provided the count of each dictionary Values should be same.

try this.
List<double> sum = new List<double>();
          int count = dictionary.ToList().First().Value.Count;
          for (int i = 0; i < count; i++)
          {
              double temp = 0;
              foreach (List<double> items in dictionary.Values)
                  temp += items[i];
              sum.Add(temp);

          }





更新后的解决方案:

下面的代码会照顾,不管每个字典值中的项目数。



updated solution:
the below code will take care, irespective of items count in each value of dictionary.

List<double> sum = new List<double>();
           int maxCount = dictionary.Values.ToList().Max(k => k.Count);
           for (int i = 0; i < maxCount; i++)
           {
               double temp = 0;
               foreach (List<double> items in dictionary.Values)
                   if (i < items.Count)
                       temp += items[i];
               sum.Add(temp);

           }


执行Karthik在此演示的方式略有不同,显示了'yield iterator模式的使用:
A slightly different way of doing what Karthik demonstrates here, showing the use of the 'yield iterator pattern:
Dictionary<int, List<double>> intdbl = new Dictionary<int, List<double>>
{
    {1, new List<double>{1.0,2.0,3.0}},
    {2, new List<double>{56.0,21.0,323.0}}
};

IEnumerable<double> listSums(List<List<double>> lstValues)
{
    // no lists : quit
    if (lstValues.Count == 0) yield break;

    // like Karthik I assume that the first list
    // item count is what to use ...
    int repcount = lstValues[0].Count;

    // no items : quit
    if (repcount == 0) yield break;

    // select only those lists that have the same number of items
    var okayvalues = lstValues.Where(lst => lst.Count == repcount);

    // this should not happen ... but ...
    if (okayvalues.Count() == 0) 
    {
        yield break;
    }

    for (int i = 0; i < repcount; i++)
    {
        yield return
            (okayvalues.Select(lst => lst[i]).Sum());
    }
}


// test in some method or EventHandler
// IEnumerable<double> is returned
var test = listSums(intdbl.Values.ToList());</double>

你可以可靠的问题假设你在这里处理的数据的状态是真实的......关键。上面的例子适用于Dictionaries,其中值(double列表)具有任何大小,但是,您可以看到,如果您基于第一个列表中使用的值的数量...您已经做出了可能的假设回来困扰你。



假设你总是希望有一些总数等于最大字典值(双打列表)的大小,实际上让编程变得更简单了:



The issue of what you can reliably assume is true about the state of the data you deal with here is ... critical. The above example would work with Dictionaries where the values (lists of double) are of any size, but, you can see that if you base the number of values to use on just the first list ... you have made an assumption that may come back to haunt you.

Assuming that you always want to have a number of "totals" equal to the size of the largest dictionary value (list of doubles), actually makes it simpler, imho, to program:

Dictionary<int, List<double>> intdbl = new Dictionary<int, List<double>>
{
    {1, new List<double>{1.0,2.0,3.0}},
    {2, new List<double>{56.0,21.0,323.0}},
    {3, new List<double>{22.23, 12.435, 99.332, 120.453, 0.993}}
};

// test in a method or EventHandler

// get the size of the largest list in 'Value Collection
int maxlistsize = intdbl.Values.ToList()
    .Select(itm => itm.Count).Max();

// allocate a new list of doubles with 'maxlistsize
// and fill it with 0.0's
List<double> totals = new List<double>(maxlistsize);
totals.AddRange(Enumerable.Repeat(0d, maxlistsize));

foreach (List<double> dbllist in intdbl.Values)
{
    for (int i = 0; i < dbllist.Count; i++)
    {
        totals[i] += dbllist[i];
    }
}

// Result:

> ? totals
Count = 5
    [0]: 79.23
    [1]: 35.435
    [2]: 425.332
    [3]: 120.453
    [4]: 0.993</double></double></double>

但问题仍然存在:您对数据结构一致性的要求是什么?使用代码时,您可以对数据采取什么假设,以及这些假设在代码中需要做些什么来防止错误并获得有意义的结果。

The question remains however: what is your requirement here for structural consistency of the data ? When your code is used, what can you assume about the data, and what do those assumptions require to do in code to prevent errors and get "meaningful" results.


这篇关于如何汇总列表&lt; double&gt;与字典中相同的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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