I have an IDictionary<string,int>
containing a distinct list of categories and respective counts with data looking something like this:
Category | Count ------------------- A | 2 B | 2 Z | 2 A_B | 1 A_B_C | 5
I'm looking for a query that sums the count of categories that start with common letters/string, so from the above the results I'm looking for is as follows:
Category | Count ------------------- A | 8 <- (a sum of A, A_B, A_B_C) B 开发者_如何学JAVA | 2 Z | 2 A_B | 6 <- (a sum of A_B, A_B_C) A_B_C | 5
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);
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 code
精彩评论