user1854438
user1854438

Reputation: 1842

Linq how to use an OR?

Can someone show me how to do an OR on a LinQ statement? For example if I have two extension methods: ByIdA() and ByIdB(). Then I want to use them similar to:

var yada = _something.Entity.ByIdA().ByIdB();

The above will call both and return rows where A and B are both true. How can I write it to use OR and returns rows where A or B are true?

I have an entity A with an Icollection of child table B, so I want to return rows from A where either A.x = 1 or B.y = 1.

Upvotes: 3

Views: 159

Answers (4)

mehrandvd
mehrandvd

Reputation: 9116

For the first part of your question could use:

var list = _something.Entity;
var result = Enumerable.Union(list.ByIdA(), list.ByIdB());

But for the second part, which seems another question, There's need to clarify the question. If you mean that each of A objects has a list of B(s) and You want all A objects which A.x==1 or A.Bs.Any(b=>b.y==1) then you could use:

var result = list.Where(a => a.x==1 || a=>a.Bs.Any(b=>b.y==1));

Upvotes: 0

Douglas
Douglas

Reputation: 54877

To return the union of two collections, you can use the Union operator.

_something.Entity.ByIdA().Union(_something.Entity.ByIdB())

If your collections don't have any common elements, you can use the Concat operator, which is cheaper since it does not check for duplicates.

Upvotes: 6

Eric Andres
Eric Andres

Reputation: 3417

You need to use a single where

_collection.Where(x => x.ByIdA() || x.ByIdB());

Upvotes: 7

Joe Enos
Joe Enos

Reputation: 40393

LINQ probably isn't the way to solve this one. Each LINQ method acts independently, so if you managed to get your OR in a chain like this, it would difficult to read, and definitely difficult to understand and debug.

You probably just want to OR the old fashioned way:

_something.Entity.Where(x => IsA(x) || IsB(x))

Upvotes: 4

Related Questions