繁体   English   中英

在Entity Framework / Linq中基于相同名称连接ID

[英]Concatenate ids based off of same Name in Entity Framework/Linq

给定具有位置ID的州列表:

location_id    name
-----------    ----
1546           Arizona
8543           Arizona
7894           Arizona
8456           Maine
8354           New York
1268           New York

我正从这张表中选择

var query = (from s in db.Locations
             //A bunch of joins and where clause to filter list
             select new { s.location_id, s.name });

我想得到一个包含以下内容的列表

    location_id    name
    -----------    ----
    1546,8543,7894 Arizona
    8456           Maine
    8354,1268      New York

我将如何处理?

我读到实体框架无法翻译String.Join,所以我必须先调用ToList(),然后从连接位置ID的列表中进行选择,但是当我这样做时,我会得到与开始时相同的列表。

如何获得想要的结果?

谢谢。

只是组:

var query2 = from l in query.AsEnumerable()
             group l by l.name into g
             select new { 
                 location_id = String.Join(",", g.Select(x=>x.location_id.ToString())),
                 name = g.Key
             };

我相信您将需要AsEnumerable()调用,因为您无法将String.Join转换为SQL。 如果您更愿意加载,当然可以改为ToList() 但是,正如@Servy指出的那样,您应该在数据库端进行分组:

var query2 = from g in query.GroupBy(l => l.name).AsEnumerable()
             select new { 
                 location_id = String.Join(",", g.Select(x=>x.location_id.ToString())),
                 name = g.Key
             };

基本上,您在这里所做的只是一个GroupBy 拉取结果后,您可以在linq中操作对象而不是查询的组结果:

var dbquery = (from s in db.Locations
                //A bunch of joins and where clause to filter list
                group s.location_id by s.name into locations
                select new { locations, name = locations.Key });

var query = dbquery.AsEnumerable()
    .Select(group => new
    {
        name = group.name,
        locations = string.Join(",", group.locations)
    });

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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