2010-01-06 26 views
5

nasıl kullanılır Burada yılında Linq ve IN yan tümcesi

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

benim kod

olduğunu. Düzeltmek için bir yöntem var mı

cevap

8

Başka bir listeyi de karşılaştırmak için kullanmalısınız.

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

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

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

Serin. Teşekkürler ... – Luke101

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

Rob Conery önce discussed Bu konuyu sahiptir.

2

Hatta daha basit:

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

çalışıyor Bu yeni [] orada koymak zorunda olduğumuz utanç verici. Sadece {1, 7, 3, 5} yapabilseydik iyi olmaz mıydı? : D –

1

Belki gibi daha bir şey:

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