2011-12-23 41 views
2

我有查詢:LINQ的順序由不訂貨

var q = 
    (
     from c in db.tblArcadeGamePlays 
     join a in db.tblProfiles on c.UserID equals a.UserID 
     where c.UserID != 0 
     orderby c.Date descending 
     select new { c.UserID, c.tblForumAuthor.Username, a.EmailAddress } 
    ) 
    .Distinct() 
    .Take(12); 

這需要正確的記錄,但不進行排序。如果我將orderby切換到asc/desc,它沒有任何影響!任何人都可以指出我能做些什麼來首先返回最新的記錄?

編輯

如果Distinct()被刪除,但是並返回結果的正確排序,但它現在遍地返回相同的用戶再次記錄(我只希望每個用戶出現一次)

+0

@Haris orderby在選擇無法編譯,因爲它是無效的linq – 2011-12-23 00:06:44

+1

什麼類型是c.Date?你的意思是說Asc和Desc的返回結果相同嗎? – Strillo 2011-12-23 00:06:58

+0

@Strillo'c.Date'是'datetime'並且是Asc和Desc返回相同的結果,即使兩個返回的記錄具有不同的日期值 – 2011-12-23 00:07:50

回答

2

這聽起來像是你想distinct列表按每個集合中的最新項目排序,對吧?

爲此,您應該使用group by。你必須order兩次,每次集中一次,再一次爲整個列表:

var q = 
    from s in 
    (
     from c in db.tblArcadeGamePlays 
     join a in db.tblProfiles on c.UserID equals a.UserID 
     where c.UserID != 0 
     select new { c.UserId, c.TblForumAuthor.Username, a.EmailAddress, c.Date } 
    ) 
    group s by new { g.UserId, g.Username, g.EmailAddress } into g 
    orderby g.OrderByDescending(s => s.Date).First().Date descending 
    select g.Key 
    ) 
    .Take(12); 

orderby部分可能會混亂,但它只是:順序組各組內的第一次約會

+1

做'orderby g.Select(s => s.Date).Min()降序'實際上可能會更有效率。 – 2012-12-09 07:06:30

-1

這個怎麼樣?

var q = (from c in db.tblArcadeGamePlays 
join a in db.tblProfiles on c.UserID equals a.UserID 
where c.UserID != 0 
select new { c.UserID, c.tblForumAuthor.Username, a.EmailAddress }) 
.OrderByDescending(c => c.Date) 
.Distinct() 
.Take(12); 
+0

語法無效,c.Date未定義(它試圖在select中查找它) – 2011-12-23 00:08:39

2

不同之處在於撤銷OrderBy。做好你的分類後,你會很好。

+1

如何選擇「區分()」記錄包含'c.Date'?這意味着每個記錄都會被視爲截然不同。每個用戶有多個'c'記錄。 – 2011-12-23 00:14:39

+0

嘗試選擇每個用戶的最後一個tblArcadeGamePlay,並按該日期排序。 – JupiterP5 2011-12-23 00:29:39

2

固定它,這是工作的查詢:

var q = (from c in db.tblArcadeGamePlays 
      join a in db.tblProfiles on c.UserID equals a.UserID 
      where c.UserID != 0 
      select new { 
       c.UserID, 
       c.tblForumAuthor.Username, 
       a.EmailAddress, 
       Date = (from d in db.tblArcadeGamePlays where d.UserID == c.UserID orderby d.Date descending select new { d.Date}).Take(1).Single().Date 
      }) 
.Distinct() 
.OrderByDescending(c=>c.Date) 
.Take(12); 

你需要指定在選擇的日期,所以我把最後日期爲特定用戶,並通過Distinct()之後訂購。很難解釋,但更有意義,如果你通讀它。