hunB
hunB

Reputation: 331

Linq GroupBy into new object

First of all I am new to Linq.

I have a list of objects named Lba that have different properties to be grouped by. My object properties are :

int aId,
int bId,
int max,
int min,
CustomObject1? Co1,
CustomObject2? Co2, 
CustomObject3? Co3

I want to group my objects into a new object LbaGroup that have the following properties

int aId,
int bId,
int max,
int min,
IList<CustomObject1> Co1,
IList<CustomObject2> Co2, 
IList<CustomObject3> Co3

I grouped my objects with the following query but it returns a List>

var query = myLbaList
  .GroupBy(a => new {a.aId, a.bId, a.max, a.min})
  .Select(a => a.ToList())
  .ToList();

I am able to build my new objects with 2 foreach loops but I was wondering if there is a direct way to achieve that with Linq.

Thank you.

Edit: My loops look like :

foreach(List<Lba> LbaList in query){
  LbaGroup myNewObject = new LbaGroup{
    Co1 = new List<CustomObject1>(),
    Co2 = new List<CustomObject2>(),
    Co3 = new List<CustomObject3>(),
  }

  foreach(Lba oldObject in LbaList){
    myNewObject.aId = oldObject.aId;
    myNewObject.bId = oldObject.bId;
    myNewObject.max = oldObject.min;

    if oldObject.Co1 != null
      myNewObject.Co1.Add(oldObject.Co1);
    if oldObject.Co2 != null
      myNewObject.Co2.Add(oldObject.Co2);
    if oldObject.Co3 != null
      myNewObject.Co3.Add(oldObject.Co3);
  }
}

Upvotes: 2

Views: 1271

Answers (1)

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186668

Something like this:

var result = myLbaList
  .GroupBy(
     a => new {a.aId, a.bId, a.max, a.min}, // Key
     a => new {a.Col1, a.Col2, a.Col3})     // Values
  .Select(chunk => new {
     // From Key
     aId = chunk.Key.aId,
     bId = chunk.Key.bId, 
     max = chunk.Key.max, 
     min = chunk.Key.min,

     // From Values
     Col1 = chunk
       .Where(item => item.Col1.HasValue) // not null items
       .Select(item => item.Col1.Value)   // CustomObject1? to CustomObject1
       .ToList(),  
     Col2 = chunk
       .Where(item => item.Col2.HasValue) 
       .Select(item => item.Col2.Value)
       .ToList(), 
     Col3 = chunk
       .Where(item => item.Col3.HasValue) 
       .Select(item => item.Col3.Value)
       .ToList(),
   })
  .ToList();

Upvotes: 6

Related Questions