Linq query to combine cell results?

I have a data table with sample data.

enter image description here

The requirement is to make this data table in such a way that it returns all rows, but for repeating rows (for example, the last two), the requirement is to combine different values ​​with a comma and return, making one record.

Example:

Gold-Silver, Metlurg 19 Nick Gordon.,

Please help me.

thanks

0
source share
1 answer

Since the "Profession" field is the only variable field, and you want to have a combined value for this field, you need the following: 1. Grouping based on Profession
2. Select records
3. Use Aggregate to Combine Profession

You also need to define a specific Row view type ( ProfessionRecord in the code below)

  var results = dataTable.AsEnumerable() .GroupBy(x=> x.Field<string>("Profession")) .Select ( grouping => new { Key=grouping.Key, CombinedProfession = grouping.Aggregate( (a,b)=> a + " " + b) }) .Select (x=> new ProfessionRecord { Id = x.Key.Id, Name = x.Key.Name, Profesion = x.CombinedProfession, }); 

VB.NET From Tool

  Dim results = dataTable.AsEnumerable().GroupBy(Function(x) x.Field(Of String)("Profession")).[Select](Function(grouping) New With { _ .Key = grouping.Key, _ .CombinedProfession = grouping.Aggregate(Function(a, b) a + " " + b) _ }).[Select](Function(x) New ProfessionRecord() With { _ .Id = x.Key.Id, _ .Name = x.Key.Name, _ .Profesion = x.CombinedProfession _ }) 

(I'm not sure how optimized it is, since VB.NET is not my first language)

You need to add the Data String Extensions link for the Field<T>(string fieldname)

+1
source

Source: https://habr.com/ru/post/1484271/


All Articles