我有Tuple<string, int>
的列表:
"dog", 25
"cat", 5
"cat", 7
"rat", 4
"dog", 10
我需要的Linq查询规则必须满足以下条件:我需要按字符串值对元组进行分组,但仅限于至少出现2次。分组元素的聚合应该是乘法。毕竟我需要聚合元素的总和。在上面的例子中,结果是25 * 10 + 5 * 7 = 285。
到目前为止,我已经尝试过其他几件事:
var query = from tuple in firstTupleList.Concat(secondTupleList)
group tuple.Item2 by tuple.Item1 into g
select Tuple.Create(g.Key, g.Aggregate((x, y) => x * y));
这是狗和猫的乘法,但是老鼠仍然在列表中是错误的。
答案 0 :(得分:3)
你应该可以这样做:
var grouped = list.GroupBy(t => t.Item1)
.Where(g => g.Count() > 1)
.Select(g => Tuple.Create(g.Key, g.Skip(1).Aggregate(g.First().Item2, (i,j) => i*j.Item2)))
.ToList();
var total = grouped.Sum(i => i.Item2);
答案 1 :(得分:0)
你走了:
List<Tuple<string, int>> list = new List<Tuple<string, int>>();
list.Add(Tuple.Create<string, int>("dog", 25));
list.Add(Tuple.Create<string, int>("dog", 10));
list.Add(Tuple.Create<string, int>("cat", 5));
list.Add(Tuple.Create<string, int>("cat", 7));
list.Add(Tuple.Create<string, int>("other", 4));
Dictionary<string, int> dic = list.
GroupBy(t => t.Item1).
Where(grp => grp.Count() > 1).
ToDictionary(grp => grp.Key,
grp => grp.Select(tuple => tuple.Item2).Aggregate((a, b) => a * b));