c# Linq -在列表中找到重复的值并选择它'

本文关键字:选择 Linq 列表 | 更新日期: 2023-09-27 18:11:48

以下是我的Linqpad示例:

 void Main()
{
    List<test> test=new List<test>();
    test.Add(new test("001","2016/10/5","11:00","A1"));
    test.Add(new test("002","2016/10/5","11:00","A1"));
    test.Add(new test("003","2016/10/4","11:00","cc")); 
    test.Add(new test("004","2016/10/4","10:00","cc"));
    test.Add(new test("005","2016/10/3","11:00","cc"));
    var list=test.GroupBy(x => new { x.BOOKING_DATE, x.PERIOD_NAME,x.BOOKING_TABLE})
    .Where(g=>g.Count()>1).Select(G=>G.Key.BOOKING_TABLE);
    list.Dump();
}
public class test{
    public string ORDERM_ID;
    public string BOOKING_DATE;
    public string PERIOD_NAME;
    public string BOOKING_TABLE;
    public test(string id,string date,string period,string table){
        this.ORDERM_ID=id;
        this.BOOKING_DATE=date;
        this.PERIOD_NAME=period;
        this.BOOKING_TABLE=table;
    }
}

我想按BOOKING_DATE和PERIOD_NAME分组查找重复的BOOKING_TABLE。

在这个例子中,我发现重复的值是"A1",但我想在列表中选择ORDERM_ID。我如何构建linq查询来做到这一点?

c# Linq -在列表中找到重复的值并选择它'

您只需要从组中选择ORDERM_ID's(然后使用SelectMany将其扁平化)

var list = test
    .GroupBy(x => new { x.BOOKING_DATE, x.PERIOD_NAME })
    .Where(g => g.Count() > 1)
    .SelectMany(g => g.Select(gg => gg.ORDERM_ID));