2010-09-08 35 views
1

我有這個簡單的查詢 - >LINQ的計數,質疑

var games = 
from p in _oListGames 
where p.Visitor == team.ID 
select p 

我想訂購此選擇與統計總場比賽的p.Visitor從該列表中有(_oListGames)

我會怎麼做?

我想通過他們當前訪問遊戲的數量來訂購var「遊戲」。

+1

我想你缺少一個標識符定義; team.ID是一個團隊還是很多團隊?這是一個更大的內部查詢?如果team.ID是一個團隊,則計數將等於列表中元素的數量,因爲所有返回的遊戲都將使其成爲訪問團隊。如果「團隊」是另一個表或集合,它應該可以加入到遊戲桌上,並從那裏馬克的答案應該工作。 – KeithS 2010-09-08 00:32:30

+0

你是對的,它應該是p.Visitor,而不是Team.ID – Marc789 2010-09-08 00:36:41

回答

3

的數量進行排序它我假設你通過每場比賽的主隊了的顧客多款遊戲的意思是爲了:

var games = 
from p in _oListGames 
where p.Visitor == team.ID 
orderby _oListGames.Count(g => p.Home == g.Visitor) 
select p; 
+0

我收到此錯誤消息:「不能隱式地將類型轉換爲長時間布爾型。」 – Marc789 2010-09-08 00:46:00

+0

我修復了我的答案。 – 2010-09-08 00:52:17

+0

工作過,謝謝! – Marc789 2010-09-08 01:00:43

1

UPDATE:好的,我想我明白你現在要做什麼。這裏有一個選擇,我認爲可能的工作:

var gameCounts = _oListGames 
    .Where(p => p.Visitor == team.ID) 
    .GroupBy(p => p.Home) 
    .Select(g => new { Opponent = g.Key, Count = g.Count() }) 
    .OrderByDescending(x => x.Count); 

這基本上是像Mark's answer但它實際上給你的結果數(而不是僅僅通過數量排序)。

+0

不是我倒下了,但我讀了它不同,他想要按計數排序,列表中有多個結果。例如。參加過20次訪問的團隊出現在之前出現過10次的團隊之前等。 – 2010-09-08 00:27:40

0
var games = from p in _oListGames where p.Visitor == team.ID select p; 
int count = games.Count(); 

或者你可以這樣做。

int count = _oListGames.Count(p=>p.Visitor == team.ID); 

通過team.ID

var sortGames = games.OrderBy(s => s.Visitor.Count());