2014-09-05 70 views
0

過濾列表。例如,我有列表如何通過列表元素

Rating rate1 = new Rating { artistID = 1, userID = 101, rating = 2 }; 
Rating rate2 = new Rating { artistID = 1, userID = 102, rating = 4 }; 
Rating rate3 = new Rating { artistID = 2, userID = 101, rating = 3 }; 
Rating rate4 = new Rating { artistID = 2, userID = 102, rating = 5 }; 
Rating rate5 = new Rating { artistID = 2, userID = 103, rating = 1 }; 
Rating rate6 = new Rating { artistID = 3, userID = 102, rating = 1 }; 
Rating rate7 = new Rating { artistID = 3, userID = 103, rating = 1 }; 

List<Rating> ratings = new List<Rating>(7); 
ratings.Add(rate1); 
ratings.Add(rate2); 
ratings.Add(rate3); 
ratings.Add(rate4); 
ratings.Add(rate5); 
ratings.Add(rate6); 
ratings.Add(rate7); 

而且我有第二個列表,

List<Rating> ratings2 = new List<Rating>(2); 
ratings2.Add(rate1); 
ratings2.Add(rate3); 

現在我想用List<Rating> ratings2過濾List<Rating> ratings

在這個CACE,我們用artistID元素篩選評級名單中,其他的字,我想包括含有artistID1和2這ratings2

上市謝謝所有的列表。

回答

3

如果你只打算來比較artistID那麼你可以做:

List<Rating> resultList = ratings.Where(r => ratings2.Select(t => t.artistID) 
              .Contains(r.artistID)) 
              .ToList(); 

以上將選擇artistIDs的第二列表ratings2做類似SELECT * from Table WHERE ID IN (1,2)

3

的比較可以使用HashSet<int>快lookup:

var r2Artists = new HashSet<int>(ratings2.Select(r2 => r2.artistID)); 
var result = ratings.Where(r => r2Artists.Contains(r.artistID)); 
+0

'Join'應該是'GroupJoin'來避免潛在的重複項目。 – Servy 2014-09-05 15:41:42

+0

你不需要'group by',只需要'into'。這將執行「GroupJoin」而不是「Join」,然後是「GroupBy」。 – Servy 2014-09-05 15:54:53

+0

感謝您指出可能與連接重複的問題,我已經完全刪除了連接方法,我更喜歡HashSet。 – 2014-09-05 16:01:01