gpt4 book ai didi

c# - 我如何通过 Linq 实现它?

转载 作者:行者123 更新时间:2023-11-30 13:49:40 25 4
gpt4 key购买 nike

例如,我有一个类如下:

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

然后,我有一个列表:

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"} ,
};

我想得到 2 个像这样的组

第 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"} ,

第 2 组:

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

所以,我只需要

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

但是现在,如果我的列表的顺序像下面这样

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"} ,
};

我怎样才能得到像这样的 3 个组

第 1 组:

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

第 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"} ,

第 3 组:

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

通过LINQ

非常感谢您的任何建议。

最佳答案

使用 GroupAdjacent 运算符,例如 one listed on Eric White's blog ,你可以这样做:

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

关于c# - 我如何通过 Linq 实现它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8742794/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com