Conditional WHERE in LINQ

风流意气都作罢 提交于 2019-12-19 07:09:19

问题


Hi any suggestions on building a LINQ statement based on search criteria?

I'll be passing in an instance of a 'SearchCriteria' class with all parameters nullable.

I then want to

if (sc.a != null)
    // add to where

if (sc.b != null)
    // add to where

The key thing is these are to be ORs not ANDs.

Any tips?

And for bonus points I'd like to use 'contains' on an int? but I can only get equals or not equals.


回答1:


Try:

.Where(x =>
    (x.a != null ? x.a == a : false) &&
    (x.b != null ? x.b == b : false));

or

.Where(x =>
    (x.a != null && x.a == a) ||
    (x.b != null && x.b == b));

Also:

.Where(x => new int[] { 1, 2, 3 }.Contains(x.i));


来源:https://stackoverflow.com/questions/12337670/conditional-where-in-linq

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!