Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
317 views
in Technique[技术] by (71.8m points)

c# - System.Linq.Dynamic - Can I use IN clause in WHERE statement

I have dynamic linq WHERE statement:

dataContext.Table.Where("id = 0 Or id = 1 Or id = 2 Or ...");

I want change to:

dataContext.Table.Where("id IN (0, 1, 2, ...)");

But it doesn′t work. How can I do this for better performance?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

From How to use “contains” or “like” in a dynamic linq query?

//edit: this is probably broken, see below
ids = new int[] {1,2,3,4};
dataContext.Table.Where("id.Contains(@0)", ids);

Aside: It is good practice to use placeholders in dynamic linq expressions. Otherwise you may open yourself to linq injection attacks (Is Injection Possible through Dynamic LINQ?)


EDIT:

actually I think I messed this up. Unfortunately I cannot test this at the moment. But I think the correct syntax in this case should be dataContext.Table.Where("@0.Contains(id)",ids);, not the other way around, and that version does not work out-of-the-box.

See here for a way to add this functionality to dynamic link. You need to modify the library for this.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...