2013-03-20 17 views
0

選擇一個物業的第一記錄我有一個類使用LINQ

class Test 
{ 
    public string FirstProp { get; set; } 
    public string SecondProp { get; set; } 
    public string ThirdProp { get; set; } 
} 

和對象

var list = new List<Test> 
{ 
    new Test { FirstProp = "xxx", SecondProp = "x2", ThirdProp = "x3" }, 
    new Test { FirstProp = "xxx", SecondProp = "x21", ThirdProp = "x31" }, 
    new Test { FirstProp = "yyy", SecondProp = "y2", ThirdProp = "y3" }, 
    new Test { FirstProp = "yyy", SecondProp = "y21", ThirdProp = "y31" }, 
    new Test { FirstProp = "xxx", SecondProp = "x22", ThirdProp = "x32" }, 
}; 

我需要選擇第一FirstProp記錄列表:

FirstProp = "xxx", SecondProp = "x2", ThirdProp = "x3" 
FirstProp = "yyy", SecondProp = "y2", ThirdProp = "y3" 

如何以最好的方式使用linq

+0

你的問題不清楚。 – MarcinJuraszek 2013-03-20 10:43:32

+0

你說你想選擇「FirstProp」,你選擇「FirstProp =」xxx「,SecondProp =」x2「,ThirdProp =」x3「」? – Popeye 2013-03-20 10:44:18

+0

我只需要FirstProp ==「xxx」的第一條記錄,首先是「yyy」,首先是「someother」等。 – Shymep 2013-03-20 10:45:19

回答

7

您可以在屬性FirstProp使用GroupBy,然後就得到First

list.GroupBy(x => x.FirstProp).Select(g => g.First()) 
+1

對,謝謝! – Shymep 2013-03-20 10:49:30

3
list.GroupBy (l => l.FirstProp).Select (l => l.First()) 

將在這裏工作,但你需要確定你需要從每個組有什麼項目(第一個是不始終是一個不錯的選擇)

0

您需要使用Distinct財產

var result = list.DistinctBy(t => t.FirstProp); 
+2

'DistinctBy'不是標準LINQ的一部分,它是[morelinq項目](http://code.google.com/p/morelinq/) – Nuffin 2013-03-20 10:51:02

+0

的擴展哦,那好吧。那麼我猜Group By是idd的路要走 – 2013-03-20 10:52:45