2010-01-06 91 views
5

這裏是我的代碼如何使用LINQ和IN子句

if (catid != 0) 
      posts = posts.Where(x => x.catid IN '1,8,2,109,23'); 

在這個代碼顯示爲一個語法錯誤。有沒有辦法解決這個問題

回答

8

你必須使用另一個列表進行比較。

List<int> cadIdFoundList = new List<int>(); 

cadIdFoundList.Add(1); 
cadIdFoundList.Add(8); 
// etc. . . 

posts.Where(x => cadIdFoundList.Contains(x.catId)); 
+0

酷。謝謝..它的工作原理 – Luke101 2010-01-06 23:43:17

5
int[] ids = new int[] { 1, 8, 2, 109, 23 }; 
var query = posts.Where(x => ids.Contains(x.catid)); 

羅布科納之前有discussed這個話題。

2

甚至更​​簡單:

var query = posts.Where(x => new[] { 1, 8, 2, 109, 23 }.Contains(x.catid)); 
+0

我們必須把那個新的[]放在那裏,真是太遺憾了。如果我們能做到{1,7,3,5},那會不會很酷? :d – 2010-01-07 16:51:11

1

也許更多的東西一樣:

HashSet<int> categories = new HashSet<int>() { 1, 2, 8, 23, 109}; 
posts = posts.Where(post => categories.Contains(post.catid));