![](/img/trans.png)
[英]How to compare a List<long> with a comma-separated ids, using linq to entities
[英]Comma-separated list into column using linq
我有两个表,它们之间具有一对多的关系,并且想要执行linq查询,该查询将从多表中获取值,并从连接到表中每个记录的值生成一个逗号分隔的列表。其他表。 我可以使用“ stuff”功能和“ for xml path”功能在sql中执行此查询。 例如,假设我具有以下表结构:
1)区
列:ID,名称
2)商店
列:ID,名称,区号
现在假设我想生成一个查询以返回以下列:district.id,district.name,stores(与该地区关联的商店的逗号分隔列表)
如何通过linq实现?
我想在一个查询中没有任何for循环来执行此操作。
其他答案考虑到您具有导航属性。 在这种情况下,您应该查看其他答案,因为在这种情况下,其他答案要简单得多。
var result =
from d in Districts
// gets all the store names in this district
let st = Stores.Where(s => s.DistrictId == d.Id).Select(s => s.Name)
select new { Name = d.Name, Id = d.Id, Stores = string.Join(",", st) }
假设您具有导航属性:
var q = from d in context.Districts
select new
{
DistrictID = d.id,
DistrictName = d.name,
Stores = String.Join(", ", d.stores.Select(s => s.name))
};
如果您使用的是Linq-to-SQL,则必须已经使用导航属性创建了ORM类,然后可以运行以下代码(我认为由于LINQ中的多元性,Store变成了Store_s_等):
var req = from dis in db.Disticts
select new {
ID = dis.id,
Name = dis.Name,
Stores =
String.Join(", ",
dis.Stores.Select( a => String.Format("{0}: {1}", a.Id, a.Name))
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.