简体   繁体   English

用linq逗号分隔的列表成列

[英]Comma-separated list into column using linq

I have two tables, with a one-to-many relationship between them and would like to perform a linq query that would take the values from the many table and generate a comma-separated list from the values that are connected to each record in the other table. 我有两个表,它们之间具有一对多的关系,并且想要执行linq查询,该查询将从多表中获取值,并从连接到表中每个记录的值生成一个逗号分隔的列表。其他表。 I can perform this query in sql using the "stuff" function and the "for xml path" function. 我可以使用“ stuff”功能和“ for xml path”功能在sql中执行此查询。 For example, suppose I have the following table structure: 例如,假设我具有以下表结构:

1) District 1)区
columns: id, name 列:ID,名称
2) Store 2)商店
columns: id, name, districtid 列:ID,名称,区号

Now suppose I wanted to generate a query to return the following columns: district.id, district.name, stores(comma-separated list of stores associated with this district) 现在假设我想生成一个查询以返回以下列:district.id,district.name,stores(与该地区关联的商店的逗号分隔列表)

How can this be achieved through linq? 如何通过linq实现?

I would like to do this without any for loops, in one query. 我想在一个查询中没有任何for循环来执行此操作。

Other answers take into account that you have navigation properties. 其他答案考虑到您具有导航属性。 When that is the case you should look at the other answers, because in that case the other answers are much simpler. 在这种情况下,您应该查看其他答案,因为在这种情况下,其他答案要简单得多。

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) }

Assuming you have navigation properties: 假设您具有导航属性:

var q = from d in context.Districts
select new
{
  DistrictID = d.id,
  DistrictName = d.name,
  Stores = String.Join(", ", d.stores.Select(s => s.name))
};

If you are using Linq-to-SQL then you must have already created your ORM classes with navigation properties and then you can just run the following code (I presume that the Store was turned into Store_s_ etc due to pluralization in LINQ): 如果您使用的是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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM