c# - 按多对多关系分组

标签 c# linq entity-framework

我有两个实体:

public class Category
{
    // Primary properties
    public int Id { get; set; }
    public string Name { get; set; }

    // Navigation properties
    public virtual ICollection<Address> Addresses { get; set; }
}

public class Address
{
    // Primary properties
    public int Id { get; set; }
    public string Name { get; set; }

    // Navigation properties
    public virtual ICollection<Category> Categories { get; set; }
}

基于一组地址 ID,我需要按类别对所有地址进行分组,包括每个地址的地址计数。

示例:

Category: {1,"WORKSHOP",{1,2}},{2,"DEALER",{1,3}}

Address:  {1,"Paul Workshop and Dealer",{1,2}}
          {2,"Joe Workshop",{1}} 
          {3,"Peter Dealer",{2}} 

如果我有地址 ID 1 和 3,我想得到:

Categories - "WORKSHOP -  Count: 1"
             "DEALER   -  Count: 2"

如果我有地址 ID 1 和 2,我想获取:类别 -

Categories - "WORKSHOP -  Count: 2"
             "DEALER   -  Count: 1" 

到目前为止我明白了,但分组依据不起作用:

var groupedAddresses = from add in addressQuery
                       where addressIds.Contains(add.Id)
                       group add by new { Category_Id = add.Categories, Address_Id = add.Id };

var result = from add in groupedAddresses 
             group add by add.Id into final
             join c in categoryQuery on final.Key equals c.Id
             select new CategoryGetAllBySearchDto
             {
                   Id = final.Key,
                   Name = c.Name,
                   SearchCount = final.Count()
              };

有什么想法吗?

谢谢。

最佳答案

int[] addressIds = { 1, 3 };

var query = from c in categoryQuery
            let searchCount = c.Addresses.Count(a => addressIds.Contains(a.Id))
            where searchCount > 0
            select new CategoryGetAllBySearchDto{
               Id = c.Id,
               Name = c.Name,
               SearchCount = searchCount
            };

关于c# - 按多对多关系分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20144096/

相关文章:

c# - 粘贴时去除所有格式的文本

c# - IDictionary[index] 是否被滥用?

c# - LINQ 等于 - 它在幕后调用什么?

sql-server - 如何选择跨群体的最高共同值(value)

json - 如何创建具有多个子行(嵌套表)的 jQuery 数据表?

c# - 我可以使用并返回 EF4 代码优先 POCO 实体作为它们的接口(interface)吗?

c# - 如何在 C# 中发现 PowerShell 脚本参数

c# - 是否有Visual Studio之类的代码编辑器控件?

c# - EF 代码优先 : Mapping nontable objects with Fluent API

c# - Foreach 扩展的更优雅的 LINQ 替代方案