Yich Lin Yich Lin - 10 months ago 50
C# Question

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

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


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){

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?

Rob Rob
Answer Source

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