Linq查询将一个表行连接到另一个表多行

时间:2015-12-03 12:02:15

标签: c# linq linq-to-entities

表名:名单

id | Name
------------
1  |xxxxx
2  |yyyyy

表名:类别

id | Nameid |Categoryid
-----------------
1  |1       |5
2  |1       |4
3  |2       |3
4  |2       |8

我需要像这样的linq查询结果

id | Name   |Categoryid
-----------------
1  |xxxx       |5,4
2  |yyyy       |3,8

我在linq下方尝试过,但它只显示了第一个类别ID

var list = from n in namelist 
           join c in category on n.id equals c.nameid 
           select new 
           { 
              n.id,
              n.name,
              c.categoryid
           }

4 个答案:

答案 0 :(得分:3)

您可以尝试String.Join

var list = namelist
    .Select(n => new { 
        n.id,
        n.name,
        categoryids = String.Join(",", category
            .Where(c => c.nameid == n.id)
            .Select(c => c.categoryid))
    });

答案 1 :(得分:3)

您可以使用Group Join执行此操作,并将String.Join组中的所有类别ID加入,如下所示: -

 var result = (from n in namelist
              join c in categories 
              on n.Id equals c.NameId into g
              select new 
                       {
                          id = n.Id,
                          Name = n.Name,
                          CategorieIds = g.Select(x => x.CategoryId)
                       }).AsEnumerable()
                         .Select(x => new 
                                   { 
                                     Id = x.id, 
                                     Name = x.Name, 
                                     CategoryIds = String.Join(",",x.CategorieIds)) 
                                   });

答案 2 :(得分:0)

使用String.Join()。我修改了你的陈述:

var list = from n in namelist 
           join c in category on n.id equals c.nameid 
           group g by new { n.id, n.name }
           select new 
           { 
              id = g.Key.id,
              Name = g.Key.name,
              Categoryid = String.Join(",", g.Select(x => x.c.categoryid))
           }

答案 3 :(得分:-2)

首先,您在NameListCategory表格上加入,然后使用ToListAsEnumerable方法将其带入对象

var list = (from n in db.NameList 
           join c in db.Category on n.id equals c.nameid 
           select new 
           { 
              id = n.id,
              Name = n.name,
              Categoryid = c.id
           }).ToList();
var list2 = from l in list
group by new {l.id, l.Name} into groupings
from g in groupings select new{
   g.Key.id,
   g.Key.Name,
   CategoryId = string.Joing(",", groupings.Where(x=>x.NameId == g.Key.id).Select(y=>y.CategoryId))
};

使用ToList从db获取数据的好处是,您只需要在数据库中进行一次查询,并在内存中获取所有必需的记录。第二个语句将按idName对这些记录进行分组,并在string.Join上应用CategoryId。请注意,如果在string.join查询中使用Linq-to-Entities方法,则会失败,因为此方法无法转换为sql表达式。