我有一個屬性類:Row, Seat
。 例如,我們有以下數據:根據另一個屬性計算屬性值(LINQ)
Row Seat
1 1
1 2
1 3
2 4
2 5
我想返回Dictionary<int,int>
包含爲重點,和數字在排座位的價值。 對於上面的例子字典將包含兩個記錄:
Key Value
1 3
2 2
我怎樣才能做到這一點?
謝謝。
我有一個屬性類:Row, Seat
。 例如,我們有以下數據:根據另一個屬性計算屬性值(LINQ)
Row Seat
1 1
1 2
1 3
2 4
2 5
我想返回Dictionary<int,int>
包含爲重點,和數字在排座位的價值。 對於上面的例子字典將包含兩個記錄:
Key Value
1 3
2 2
我怎樣才能做到這一點?
謝謝。
list.GroupBy(x => x.Row)
.ToDictionary(x => x.Key, x => x.Count());
謝謝。這個解決方案的性能怎麼樣? – user348173 2012-03-14 09:32:48
沒有'.ToArray()'。 OP想要一個字典,而不是一個數組。 – Steven 2012-03-14 09:33:20
@Steven謝謝。 – 2012-03-14 09:34:06
,這不是太參與:
var seatings = new List<Seatings>(); /* list of your class instances */
seatings.GroupBy(s => s.Row).ToDictionary(s => s.Key, s => s.Count());
分組按行產生組的集合,每個組都有一個Key
等於行,可以列舉以獲得該行中的所有底座。你可以用ToDictionary
直接製作字典。
您的意思是**連續座位**的最大數量作爲價值返回? – Zeina 2012-03-14 09:30:55
像在SQL中一樣使用GroupBy()和Count()。 – 2012-03-14 09:31:34
@Zenia:我更新了一個例子。 – user348173 2012-03-14 09:33:06