如何将groupby查询转换为linq并在执行时计算其他东西?

时间:2016-04-20 06:51:42

标签: c# sql linq

我有这个SQL查询,我想将其转换为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]

我想查看最后一个日期,如果是最新日期,那么我必须将其标记为' live'?

1 个答案:

答案 0 :(得分:2)

由于您希望将结果复制到DataTable,因此此查询会执行Sql查询中指定的内容并将结果复制到DataTable

DataTable dt = new DataTable();

dt.Columns.Add("Scheme_Code", typeof(string));
dt.Columns.Add("Scheme_Name", typeof(string));
dt.Columns.Add("FundFamily", typeof(string));
dt.Columns.Add("LastDate", typeof(DateTime));

var table = MFDatas.GroupBy(g=> new { Scheme_Code, Scheme_Name, FundFamily})
                   .Select(s=> 
                   { 
                        var row = dt.NewRow();
                        row["Scheme_Code"] =  s.Key.Scheme_Code, 
                        row["Scheme_Name"] = s.Key.Scheme_Name, 
                        row["FundFamily"] = s.Key.FundFamily, 
                        row["LastDate"] = s.Max(m=>m.Date) 
                    })                  
                   .OrderBy(o=>o.Field<string>("Scheme_Code"))
                   .Distinct()
                   .CopyToDataTable();