使用linq将逗号分隔的列表放入列中

本文关键字:列表 分隔 linq 使用 | 更新日期: 2023-09-27 18:14:50

我有两个表,它们之间有一对多的关系,并且想执行一个linq查询,该查询将从many表中获取值,并从连接到另一个表中的每个记录的值生成一个逗号分隔的列表。我可以使用"stuff"函数和"for xml path"函数在sql中执行此查询。例如,假设我有以下表结构:


1)区列:id, name
2)存储
列:id, name, distritid

现在假设我想生成一个查询来返回以下列:区。Id,地区名称,商店(与该地区相关的商店的逗号分隔列表)

如何通过linq实现这一点?

我希望在一个查询中不使用任何for循环。

使用linq将逗号分隔的列表放入列中

其他的答案考虑到你有导航属性。在这种情况下,你应该看看其他答案,因为在这种情况下,其他答案要简单得多。

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