user576510
user576510

Reputation: 5915

Linq query to combine cell results?

I have a data table with this sample data.

enter image description here

Requirment is to make this data table so it returns all rows but for duplicate rows (last two for example) requirement is to combine there different values with a comma and return by making it one record.

For Example:

Gold-Silver,Metllurgist 19 Nick Gordon . . . . .

Please help me.

THANKS

Upvotes: 0

Views: 207

Answers (1)

Tilak
Tilak

Reputation: 30718

As Profession field is the only changing field, and you want combined value for this field, Following is needed
1. Grouping based on Profession
2. Select the records
3. Use Aggregate for combining Profession

You also need to define a concrete type to represent Row (ProfessionRecord in 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 the 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 am not sure how much it is optimized as VB.NET is not my first language)

You need to add reference of Data Row Extensions for the method Field<T>(string fieldname)

Upvotes: 1

Related Questions