本文介绍了LINQ聚合列表中的项目,并连接一个属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请对LINQ假人好一点...假设我有8行数据,如下所示:

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       |
+-------------------+

作为8个项目 IList< Worktype> 集合,其中 Worktype 看起来像

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

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

我想要的是按ID进行汇总,以获取具有3个工作类型的列表,每个工作类型都是以分号分隔的排序列表,例如:

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                  |
+-------------------------------------+

??

推荐答案

仅按 Id 分组,使用 string.Join 汇总在每个组中.

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

这篇关于LINQ聚合列表中的项目,并连接一个属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-10 16:17