C#Linq - 在列表中查找重复值并选择它的id

时间:2016-10-06 01:42:28

标签: c# linq

这是我的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查询来执行此操作?

1 个答案:

答案 0 :(得分:6)

您只需从组中选择ORDERM_ID(然后使用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));