为什么这个linq查询不返回不同的代码?

时间:2016-04-20 09:50:38

标签: c# linq

我想要所有唯一Scheme_Codes的列表,但我无法编写查询。我试过这个,但我很困惑这个查询有什么问题。

 var queryresult = db.MFData.GroupBy(x => new { Scheme_Name = x.Scheme_Name, Scheme_Code = x.Scheme_Code, FundFamily = x.FundFamily, Date = x.Date })
                   .Select(group => new
                   {
                       Scheme_name = group.Key.Scheme_Name,
                       Scheme_Code = group.Key.Scheme_Code,
                       FundFamily = group.Key.FundFamily,
                       Date = group.Max(x => x.Date),
                       count = group.Select( x =>  x.Scheme_Code).Distinct().Count()
                   }
                   ).OrderBy(x => x.Scheme_Code);

我有这个查询,但我不知道如何将其转换为linq

SELECT [Scheme_Code],[FundFamily],[Scheme_Name],
 MAX([Date]) as LastDate   
 FROM [MFD].[dbo].[MFDatas]   
 GROUP BY [Scheme_Code],[Scheme_Name], [FundFamily]  
 ORDER BY [Scheme_Code]

1 个答案:

答案 0 :(得分:1)

您所要做的就是省略groupby子句中的日期:

var queryresult = db.MFData.GroupBy(x => new 
    { 
        Scheme_Name = x.Scheme_Name, 
        Scheme_Code = x.Scheme_Code, 
        FundFamily = x.FundFamily 
    }).Select(group => new
    {
        Scheme_name = group.Key.Scheme_Name,
        Scheme_Code = group.Key.Scheme_Code,
        FundFamily = group.Key.FundFamily,
        Date = group.Max(x => x.Date),
        count = group.Select(x => x.Scheme_Code).Distinct().Count()
    }).OrderBy(x => x.Scheme_Code);