0

I have few records like below in a collection where two records have same item name and description(example: sample1 and item1) but some other fields are different,

1.sample1     item1   Rule2      Rule2msg        iteminfo2

2.sample1     item1   test1      testrule        iteminfo1

I need to group above records in linq in such a way that output is like below ,

Sample1,
item1,
{
    Rule2, 
    Rule2msg, 
    iteminfo2
},    
{
    testrule1 , 
    testrulemsg,
    iteminfo1
}

Basically what i am trying to achieve is since first two fields (itemName and Desc) is same , group them into single item and nest the remaining fields under the item so that item name is not duplicated and doesnt appear twice and appears as a single item. Any help is much appreciated

I have tried this

Itm.GroupBy(x => x.ITEM_NAME).Select(x => x.ToList()).ToList();

it groups items , but as two records not as single item as what i expect.

Rafalon
  • 4,450
  • 2
  • 16
  • 30
CodeDada
  • 425
  • 1
  • 11
  • 24
  • Does the following link answer your question ? https://stackoverflow.com/questions/847066/group-by-multiple-columns?rq=1 check `.GroupBy(x => (x.Column1, x.Column2))` – Rafalon Jan 18 '18 at 09:47
  • @Rafalon this will still return two items under one item .but not as what i expect – CodeDada Jan 18 '18 at 10:00
  • So your question is about grouping them in a special structure ? How did you expect using `.Select(x => x.ToList())` to do this ? – Rafalon Jan 18 '18 at 10:23

1 Answers1

0

You should group the records on both the itemName and Desc columns.

Itm.GroupBy(x => new {x.ITEM_NAME, x.Desc}).Select(x => x.ToList()).ToList();
ctyar
  • 931
  • 2
  • 10
  • 22