2016-02-12 44 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(); 
相關問題