LINQ aggregate items in a list, concatenate a property

五迷三道 提交于 2021-02-17 04:09:10

问题


Please be kind to a LINQ dummy... Say I have 8 rows data like this:

+-------------------+
|  ID   WORKTYPEDESC|
+-------------------+
| 1     plumber     |
| 1     carpenter   |
| 1     electrician |
| 2     juggler     |
| 2     mime        |
| 3     writer      |
| 3     actor       |
+-------------------+

As an 8-item IList<Worktype> collection where Worktype looks like

public class Worktype
{
  public int Id { get; set; }
  public string WorktypeDesc { get; set; }
}

And what I want is to aggregate by Id to get a list with 3 Worktypes, each with a WorktypeDesc being a sorted, semicolon-delimited list, like this:

+-------------------------------------+
| ID    WORKTYPEDESC                  |
+-------------------------------------+
| 1     carpenter;electrician;plumber |
| 2     juggler;mime                  |
| 3     actor;writer                  |
+-------------------------------------+

??


回答1:


Just group by Id, use string.Join to aggregate within each group.

IEnumerable<Worktype> source = ...;
var query = source.GroupBy(
    x => x.Id,
    (id, g) => new Worktype
    {
        Id = id,
        WorktypeDesc = string.Join(";", g.Select(x => x.WorktypeDesc).OrderBy(x => x))
    });


来源:https://stackoverflow.com/questions/29305537/linq-aggregate-items-in-a-list-concatenate-a-property

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!