关于IDictionary的C#Linq Sum查询

时间:2011-04-26 20:51:42

标签: c# linq

我有一个IDictionary<string,int>包含一个不同的类别列表和相应的计数,数据看起来像这样:

Category  |  Count
-------------------
A         |    2
B         |    2
Z         |    2
A_B       |    1
A_B_C     |    5

我正在寻找一个查询,它总结以普通字母/字符串开头的类别数,所以从上面我要找的结果如下:

Category  |  Count
-------------------
A         |    8     <- (a sum of A, A_B, A_B_C)
B         |    2
Z         |    2
A_B       |    6     <- (a sum of A_B, A_B_C)
A_B_C     |    5

2 个答案:

答案 0 :(得分:6)

var d = new Dictionary<string, int>()
{
    { "A", 2 },
    { "B", 2 },
    { "Z", 2 },
    { "A_B", 1 },
    { "A_B_C", 5 },
};

var d2 = d.Select(kvp => new KeyValuePair<string, int>(
                kvp.Key,
                d.Where(k => k.Key.StartsWith(kvp.Key))
                 .Sum(k => k.Value)))
          .ToDictionary(kvp => kvp.Key, kvp => kvp.Value);

答案 1 :(得分:2)

Dictionary<string, int> data = new Dictionary<string,int>();

data.Add("A", 2);
data.Add("B", 2);
data.Add("Z", 2);
data.Add("A_B", 1);
data.Add("A_B_C", 5);

data.Dump();

    var result = from d in data
                 select new {Key = d.Key, Sum = (from dt in data where dt.Key.StartsWith(d.Key) select dt).Sum(x=>x.Value)};

result.Dump();

Linqpad代码