简体   繁体   中英

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. I can perform this query in sql using the "stuff" function and the "for xml path" function. For example, suppose I have the following table structure:

1) District
columns: id, name
2) Store
columns: id, name, districtid

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)

How can this be achieved through linq?

I would like to do this without any for loops, in one query.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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