Home > Software engineering >  Can I Group by (LINQ) and add a field and concat another?
Can I Group by (LINQ) and add a field and concat another?

Time:10-16

I'm reading data from an excel sheet and (after some processing) I'm placing it into a class:

public class Record
{
        public string partNo { get; set; }
        public float quantity { get; set; }
        public string designator { get; set; }
}

This is what the data looks like:

record[0]=new Record { partNo = "123456789", quantity = 2, designator = "C1 C2 " };
record[1]=new Record { partNo = "333333333", quantity = 2, designator = "D1 D2 " };
record[2]=new Record { partNo = "123456789", quantity = 3, designator = "C10 C12 C15 " };
record[3]=new Record { partNo = "222222222", quantity = 5, designator = "Q5 Q6 Q10 Q22 Q50 " };

Is there a way to group the partNo that have the same data and add the quantities and concat the designators? like...

record[0]=new Record { partNo = "123456789", quantity = 5, designator = "C1 C2 C10 C12 C15 " };
record[1]=new Record { partNo = "333333333", quantity = 2, designator = "D1 D2 " };
record[3]=new Record { partNo = "222222222", quantity = 5, designator = "Q5 Q6 Q10 Q22 Q50 " };

I found a similar post but not quite: Group by in LINQ

My c# skills are beginner and my Linq experience is non-existence...lol.

Any help is appreciated. Thanks

CodePudding user response:

You can use Enumerable.GroupBy to group and project the elements to a new form:

IEnumerable<Record> groupedRecords = records.GroupBy(
  record => record.partNo, 
  (groupKey, records) => 
    new Record
    { 
      partNo = groupKey, 
      quantity = records.Sum(record => record.quantity), 
      designator = string.Concat(
        records.Select(record => record.designator)) 
    });
  • Related