shenhengbin shenhengbin - 10 days ago 5
C# Question

How can I implement it by Linq?

For exsample , I have a class like below.

public class SampleItem
{
public string QCD { get; set; }
public string CCD { get; set; }
public string ITYPE { get; set; }
}


Then , I have a list like ,

var lstTest = new List<SampleItem>() {

new SampleItem(){ QCD = "Q1" , CCD = "C1" , ITYPE = "A"} ,
new SampleItem(){ QCD = "Q1" , CCD = "C2" , ITYPE = "A"} ,
new SampleItem(){ QCD = "Q1" , CCD = "C3" , ITYPE = "A"} ,

new SampleItem(){ QCD = "Q1" , CCD = "C1" , ITYPE = "B"} ,
new SampleItem(){ QCD = "Q1" , CCD = "C2" , ITYPE = "B"} ,
};


I want to get 2 Groups like

Group 1 :

new SampleItem(){ QCD = "Q1" , CCD = "C1" , ITYPE = "A"} ,
new SampleItem(){ QCD = "Q1" , CCD = "C2" , ITYPE = "A"} ,
new SampleItem(){ QCD = "Q1" , CCD = "C3" , ITYPE = "A"} ,


Group 2 :

new SampleItem(){ QCD = "Q1" , CCD = "C1" , ITYPE = "B"} ,
new SampleItem(){ QCD = "Q1" , CCD = "C2" , ITYPE = "B"} ,


So , I just need

lstTest.GroupBy (p=>new {p.QCD ,p.ITYPE});


But now , If My List's order like below

var lstTest = new List<SampleItem>() {

new SampleItem(){ QCD = "Q1" , CCD = "C1" , ITYPE = "B"} ,
new SampleItem(){ QCD = "Q1" , CCD = "C2" , ITYPE = "B"} ,

new SampleItem(){ QCD = "Q1" , CCD = "C1" , ITYPE = "A"} ,
new SampleItem(){ QCD = "Q1" , CCD = "C2" , ITYPE = "A"} ,
new SampleItem(){ QCD = "Q1" , CCD = "C3" , ITYPE = "A"} ,

new SampleItem(){ QCD = "Q1" , CCD = "C1" , ITYPE = "B"} ,
new SampleItem(){ QCD = "Q1" , CCD = "C2" , ITYPE = "B"} ,
};


How can I get 3 Groups like

Group 1 :

new SampleItem(){ QCD = "Q1" , CCD = "C1" , ITYPE = "B"} ,
new SampleItem(){ QCD = "Q1" , CCD = "C2" , ITYPE = "B"} ,


Group 2 :

new SampleItem(){ QCD = "Q1" , CCD = "C1" , ITYPE = "A"} ,
new SampleItem(){ QCD = "Q1" , CCD = "C2" , ITYPE = "A"} ,
new SampleItem(){ QCD = "Q1" , CCD = "C3" , ITYPE = "A"} ,


Group 3 :

new SampleItem(){ QCD = "Q1" , CCD = "C1" , ITYPE = "B"} ,
new SampleItem(){ QCD = "Q1" , CCD = "C2" , ITYPE = "B"} ,


By Linq ?

Thank you for kindly advice .

Ani Ani
Answer

Using a GroupAdjacent operator, such as the one listed on Eric White's blog, you can do:

var groupedItems = lstTest.GroupAdjacent(p => new { p.QCD, p.ITYPE });
Comments