我想通过以下元组进行分组:
List<Tuple<string, string, int>> tu = new List<Tuple<string, string, int>>();
tu.Add(new Tuple<string, string, int>("a", "b", 201601));
tu.Add(new Tuple<string, string, int>("a", "b", 201602));
tu.Add(new Tuple<string, string, int>("a", "b", 201603));
tu.Add(new Tuple<string, string, int>("c", "d", 201601));
tu.Add(new Tuple<string, string, int>("c", "d", 201602));
结果应该在新的元组中看起来像这样:
//Item1, Item2, Min(Item2), Max(Item3)
List<Tuple<string, string, int, int>> newtu = new List<Tuple<string, string, int, int>>();
a,b,201601,201603
c,d,201601,201602
你能帮我吗?
答案 0 :(得分:2)
from t in tu
group t by new { t.Item1, t.Item2 } into g
select Tuple.Create(g.Key.Item1, g.Key.Item2, g.Min(t => t.Item3), g.Max(t => t.Item3));
建议:不要在C#中使用元组。以往
答案 1 :(得分:1)
按匿名类型分组,然后在群组中使用Min
+ Max
:
List<Tuple<string, string, int, int>> newtu = tu
.GroupBy(t => new { t1 = t.Item1, t2 = t.Item2 })
.Select(g => Tuple.Create(g.Key.t1, g.Key.t2, g.Min(t => t.Item3), g.Max(t => t.Item3)))
.ToList();