Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Linq - Find Duplicate value in list and select it's id

Tags:

c#

linq

Here is my Linqpad example:

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

I want group by BOOKING_DATE and PERIOD_NAME to find duplicate BOOKING_TABLE.

In this example ,I find the duplicate value is "A1", But I want select the ORDERM_ID in list. How can I build a linq query to do this?

like image 348
Yich Lin Avatar asked Mar 10 '23 23:03

Yich Lin


1 Answers

You simply need to select the ORDERM_ID's from the group (and then flatten it with 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));
like image 141
Rob Avatar answered Mar 23 '23 09:03

Rob