Linq to Sql Group By 没有计数

Linq to Sql Group By without count

我有一个 linq to sql 并且一直在研究如何使用 linq to sql 对结果进行分组。我只看到其中包含计数和总和的样本。我的模型是每个客户订单都有多种注释,并且可以有多个注释。现在它会列出所有客户订单,如果它有多个注释,则会多次列出。

如何在没有 sums/counts 聚合

的情况下使用 Linq 中的分组依据到 Sql

我试过:

public IQueryable<object> getAllamcase()
    {
        try
        {
            var q = (from c in _context.Customer
                     join am in _context.table2 on c.id equals am.id
                     join ampn in _context.table3 on am.id equals ampn.id
                     join ay in _context.tabl4 on am.id equals ay.id
                     join oim in _context.table5 on am.id equals oim.id
                     group c.FileNum by new
                     {
                         FileNum = c.order,
                         assignmentdt = am.Assignment_DT,
                         oimname = oim.FullName,
                         notes = ampn.ProgressNotes,
                         years = ay.AMYear
                     }).AsQueryable();

            return q;
        }
        catch (Exception ex)
        {
            _logger.LogError("Could not get......", ex);
            return null;
        }
    }

我的结果看起来像多个 jsons

Customer  notes
1               notes 1
1               notes 2
1               notes 3
2               notes 1
2               notes 2  

我只想 return 合一 json 喜欢

 Customer  notes
1              notes 1
               notes 2
               notes 3

2              notes 1
               notes 2

你的问题不清楚,但正如我@GertArnold 所说,如果你想加载客户的笔记,你应该使用导航属性。另外,请看naming conventions。如果您正确命名变量等,您的代码将更加清晰。但是根据你的问题header,我可以建议你关注。假设您有 Note class:

public class Note
{
    public int CustomerId { get; set; }
    public string NoteName { get; set; }
}

您有如下注释列表:

List<Note> notes = new List<Note>
{
    new Note { CustomerId = 1, NoteName = "note 1" },
    new Note { CustomerId = 1, NoteName = "note 2" },
    new Note { CustomerId = 1, NoteName = "note 3" },
    new Note { CustomerId = 1, NoteName = "note 4" },
    new Note { CustomerId = 2, NoteName = "note 1" },
    new Note { CustomerId = 2, NoteName = "note 2" },
    new Note { CustomerId = 3, NoteName = "note 1" },
};

如果您想从此列表中获取 CustomerId-s 和相关注释,您可以通过对它们进行分组来轻松实现:

var result = notes
    .GroupBy(m => m.CustomerId)
    .Select(g => new
    {
        CustomerId = g.Key,
        Notes = g.Select(m => m.NoteName).ToList()
    });

结果将是:

CustomerId  ||  NoteName
1               note 1
                note 2
                note 3
                note 4
2               note 1
                note 2
3               note 1

希望对你有所帮助