开发者

Best Practice for Linq Where with OR clause?

开发者 https://www.devze.com 2023-02-02 20:55 出处:网络
Ive found using Linq, to do a WHERE selector with multiple clauses separated with an \'AND\' is easy peasy - however ive written the below code to do the equivilent of a \'WHERE\' query with an \'OR\'

Ive found using Linq, to do a WHERE selector with multiple clauses separated with an 'AND' is easy peasy - however ive written the below code to do the equivilent of a 'WHERE' query with an 'OR' seperating each case.开发者_开发技巧

Can anyone suggest anything better as it feels abit crappy to concat each time.

    var foo = new int[] { 0, 0, 1, 1, 2, 2, 3, 3 };
    var bar = new int[] { 0, 2 };

    var hum = new List<int>();

    foreach (int i in bar)
        hum.AddRange(foo.Where(a => a == i));

edit: Changed concat for AddRange...


Well, that code won't even work. Concat doesn't modify the sequence it's called on - it returns a new sequence which is the concatenation of two others.

In this case I think you want:

var values = foo.Where(x => bar.Contains(x));

That's specific to this case, of course - there's no "general" OR clause in LINQ.


Use the following:

var hum = bar.Select(x => foo.Where(y => y == x)).SelectMany(z => z).ToList();
0

精彩评论

暂无评论...
验证码 换一张
取 消