问题
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