我有一个像这样的课:

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

该表中包含以下数据:
c# - 在C#中的LINQ中按多列分组-LMLPHP

我想为以下viewModel类按IssuerName和DateOfIssue对它们进行分组:
public class ViewModel
{
   public string IssuerName { get; set; }
   public DateTime DateOfIssue { get; set; }
   public List<string> Books { get; set; }
}

数据将显示如下:(成功分组后,屏幕快照数据将替换为先前的表数据)
c# - 在C#中的LINQ中按多列分组-LMLPHP

特别注意:根据我的期望,我的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
                };

最佳答案



可能是因为图书属性是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

10-06 13:02