2012-12-21 185 views
1

重複行我現在必須爲每個「FileStreamID」複式記錄,但我只是想根據最新的「請求日期」掌握LINQ

這裏一個不同的一個是我現在有:

var resultx = from v in ctx.vEmailSents 
          where v.Lab_ID == 44 
           && v.UploadDate >= this.BeginDate 
          select new 
          { 

           FileStreamID = v.FileStream_ID, 
           UploadDate = v.UploadDate, 
           RequestDate = v.DateSent, 
           TypeDesc = v.TypeDesc 
          }; 

,現在我獲得約33條記錄(但我應該只得到12)

我怎樣才能將其更改爲只給我FILESTREAM ID不同行?

回答

4

集團的vEmailSent對象通過FileStream_ID,並從每個組項目與最新的日期選擇:

var resultx = from v in ctx.vEmailSents 
       where v.Lab_ID == 44 
        && v.UploadDate >= this.BeginDate 
       group v by v.FileStream_ID into g 
       select g.OrderByDescending(x => x.DateSent) 
         .FirstOrDefault() into lastV 
       select new { 
         FileStreamID = lastV.FileStream_ID, 
         UploadDate = lastV.UploadDate, 
         RequestDate = lastV.DateSent, 
         TypeDesc = lastV.TypeDesc       
       }; 
+1

謝謝!我認爲那樣做了!所有的人都熱衷於所有強大的LINQ神@lazyberezovsky! –

+0

順便說一句,被刪​​除的帖子,如果選擇新的{x ...}僅包含要比較的字段,則適用。經常.Distinct()是更好的解決方案 –

0
var results = resultx 
    .GroupBy(x => x.FileStreamID) 
    .Select(g => g.OrderByDescending(x => x.RequestDate).First());