Linq查询使用group by子句从数据库获取数据

时间:2016-10-17 12:10:26

标签: linq asp.net-mvc-4

我正在开发MVC4应用程序。我最终得到了一个复杂的场景。我在sql中有以下表。

upld_Id     Label         Value          Commited
1000        DocNumber     123            0
1000        ExpiryDate    01/01/2016     0
1000        Docnumber     456            1
1000        ExpiryDate    01/01/2018     1

我应该以下面的格式获得输出。

upld_Id     Label         OldValue      NewValue 
1000        Docnumber     123           456
1000        ExpiryDate    01/01/2016    01/01/2018

我尝试如下。

var logDetails = (from c in db.logTable
                  join tbl in db.MetaTable on c.id equals tbl.id
                  //GroupBy
                  where  (c.commited==false || c.commited==true) 
                  select new ClassName
                  {
                      //Get Values
                  }).toList();

这是我在LINQ中尝试过的。我不知道如何在这里应用LINQ

var logDetails = (from c in db.ts_upldlog_content
                                      join tbl in db.ts_upld_doc on c.upld_docid equals tbl.upld_docid
                                      join doc in db.tm_doc_type on tbl.upld_doctypeid equals doc.doc_typeid
                                      where c.upld_docid==data
                                 group c by c.upld_contentlabel into grouping
                                 select new logdetails
                                 {
                                    updatedOn=c.updatedOn //Here Error
                                    contentLabel=grouping.Key,
                                    oldValue = grouping.FirstOrDefault(x => x.commited ==false).upld_contentvalue,
                                    newValue = grouping.FirstOrDefault(x => x.commited == true).upld_contentvalue,
                                 }).ToList();

有人可以告诉我这在LINQ中是否可行?感谢

3 个答案:

答案 0 :(得分:1)

您需要按Label对结果进行分组,然后为每个oldValuenewValue检索与谓词匹配的项目commited == 1 / {{1 }}):

commited == 0

答案 1 :(得分:1)

您可以使用子查询获得预期结果:

var logDetails = (from i in db.Tbl
                  where 
                    i.Commited == false
                  select new ClassName
                  {
                    i.Id,
                    i.Label,
                    OldValue = i.Value,
                    NewValue = (db.Tbl.Where(t => t.Id == i.Id && t.Comitted == true).Select(t => t.Value).FirstOrDefault())
                  }).ToList();

答案 2 :(得分:1)

我将GroupBy(upld_Id,Label)改为新的匿名类型......

var query = db.logTable.GroupBy(l => new { l.upld_Id, l.Label })
                       .Select(g => new
                       {
                           upld_Id = g.Key.upld_Id,
                           Label = g.Key.Label,
                           OldValue = g.FirstOrDefault(o => o.Commited == 0).Value, 
                           NewValue = g.FirstOrDefault(o => o.Commited == 1).Value,
                       })
                       .ToList();