2010-01-06 89 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));