表名:名单
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
}
答案 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)
首先,您在NameList
和Category
表格上加入,然后使用ToList
或AsEnumerable
方法将其带入对象
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获取数据的好处是,您只需要在数据库中进行一次查询,并在内存中获取所有必需的记录。第二个语句将按id
和Name
对这些记录进行分组,并在string.Join
上应用CategoryId
。请注意,如果在string.join
查询中使用Linq-to-Entities
方法,则会失败,因为此方法无法转换为sql表达式。