2016-02-12 56 views
1

我想组由下列元组:C#列表<组<字符串,字符串,整数>>组由最小值最大值INT

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

我很好奇为什么你会说永远不会使用元组?当然,对于私人/内部成员来说,这是可以接受的,因为你可以维护上下文 – sr28

+0

那我该用什么? – Yonnr

+0

@ sr28元组很好,例如在Python中。但是C#元组不是自描述的数据结构 - 它们具有丑陋的Item1,Item2,Item3属性,它们对存储在那里的数据一无所知。与创建元组一样 - 参数没有名称,很容易将值放在错误的位置。如果你想使你的代码不那么干净和可读,那么元组是好的,否则我会建议使用匿名对象或创建好的自描述类。 –

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(); 
相关问题