2016-10-06 54 views
3

這是我Linqpad例如:C#的LINQ - 在列表中查找重複的值,然後選擇它的id

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查詢來做到這一點?

回答

5

您只需從該組中選擇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)); 
+0

這個答案可以work.Thanks很多。 –

相關問題