在C#LINQ中按多列分组

时间:2016-11-23 03:34:55

标签: c# asp.net-mvc entity-framework linq

我有一个如下课程:

public class ActualClass
{
    public string BookName { get; set; }
    public string IssuerName { get; set; }
    public DateTime DateOfIssue { get; set; }
    public bool Status { get; set; }
}

表中有以下数据: enter image description here

我想通过 IssuerName DateOfIssue 为以下viewModel类对它们进行分组:

public class ViewModel
{
   public string IssuerName { get; set; }
   public DateTime DateOfIssue { get; set; }
   public List<string> Books { get; set; }
}

数据将显示如下:(成功分组后,屏幕截图数据将替换为上一个表数据enter image description here

特别注意: 根据我的期望,我的ViewModel有什么问题吗?

我在尝试了一些stackoverflow的答案之后尝试了很多,但没有一个对我有用。任何帮助将受到高度赞赏。

我试过的代码:

var viewmodel = from b in db.BookIssues
                group b by new
                {
                    b.IssuerName,
                    b.DateOfIssue
                }
                into g
                select new ViewModel()
                {
                    Name = g.key.IssuerName,
                    DateOfIssue = g.Key.DateOfIssue,
                    Books = g.ToList() //Actually this line of code is not working
                };

2 个答案:

答案 0 :(得分:12)

  

Books = g.ToList()//实际上这行不起作用

可能是因为图书属性的类型为List<string>,而不是List<ActualClass>

您可以尝试此查询,我添加了b.Select(bn => bn.BookName).ToList()仅提取图书的名称:

var books = new List<ActualClass>
{
   new ActualClass { BookName = "A", DateOfIssue = new DateTime(2015, 10, 10, 10, 10, 0), IssuerName = "1" },
   new ActualClass { BookName = "B", DateOfIssue = new DateTime(2015, 10, 10, 10, 10, 0), IssuerName = "1" },
   new ActualClass { BookName = "C", DateOfIssue = new DateTime(2015, 10, 10, 10, 10, 0), IssuerName = "1" },
   new ActualClass { BookName = "D", DateOfIssue = new DateTime(2015, 10, 10, 10, 10, 0), IssuerName = "2" },
   new ActualClass { BookName = "E", DateOfIssue = new DateTime(2015, 10, 10, 12, 10, 0), IssuerName = "2" },
   new ActualClass { BookName = "F", DateOfIssue = new DateTime(2015, 10, 10, 12, 10, 0), IssuerName = "2" }
};

var result = books.GroupBy(x => new { x.IssuerName, x.DateOfIssue })
                .Select(b => new ViewModel
                {
                    Books = b.Select(bn => bn.BookName).ToList(),
                    // Accessing to DateOfIssue and IssuerName from Key.
                    DateOfIssue = b.Key.DateOfIssue,
                    IssuerName = b.Key.IssuerName
                });

我分组为:x.IssuerName, x.DateOfIssue。我通过以下方式在GroupBy()中传递匿名类型来做到这一点:x => new { x.IssuerName, x.DateOfIssue }

现在它们处于密钥状态,您可以从SELECT语句中的KEY访问 IssuerName DateOfIssue ,如下所示:b.Key.IssuerNameb.Key.DateOfIssue

答案 1 :(得分:3)

如果您需要从小组结果中选择图书清单,则需要Books = v.Select(c=>c.BookName).ToList()还要注意,如果您有发布日期时间,则可能需要使用{{1}仅按日期部分进行分组功能。如果您只存储日期,则可以忽略此功能。

EntityFunctions.TruncateTime