user70192
user70192

Reputation: 14204

C# - LINQ Statements with OR clauses

I am trying to use LINQ to return a list of tasks that are in one of three states. These states are:

10 - Completed 11 - Incomplete 12 - Skipped

The state is available through a property called "TaskStateID". I can do this in LINQ with just one state as shown here:

var filteredTasks = from task in tasks
                    select task;

// Do stuff with filtered tasks

string selectedComboBoxValue = GetFilterComboBoxValue();
if (selected ComboBoxValue == 3)
{
  filteredTasks = filteredTasks.Where(p => p.TaskStateID == 10); // How do I use an 'OR' here to say p.TaskStateID == 10 OR p.TaskStateID == 11 OR p.TaskStateID == 12
}

As shown in the comment above, how do I use an 'OR' in a LINQ statement to say p.TaskStateID == 10 OR p.TaskStateID == 11 OR p.TaskStateID == 12?

Thank you

Upvotes: 37

Views: 67839

Answers (6)

Rony
Rony

Reputation: 9511

var taskIds = new[]{10, 11, 12}

var selectedTasks = filteredTasks.Where(p => taskIds.Contains(p.TaskStateID))

Upvotes: 20

Joel Coehoorn
Joel Coehoorn

Reputation: 415800

The easiest way:

.Where(p => p.TaskStateID == 10 || p.TaskStateID == 11 || p.TaskStateID == 12)

Or you could also do something like this:

var states = new int[] {10,11,12};
filteredTasks = filteredTasks.Join(states, p => p.state, s => s, (p, s) => p);

Upvotes: 3

devoured elysium
devoured elysium

Reputation: 105077

filteredTasks.Where(p => (p.TaskStateID == 10 || p.TaskStateID == 11 || p.TaskStateID == 12))

Upvotes: 1

zneak
zneak

Reputation: 138051

Very simple: you use logical ORs.

filteredTasks.Where(p => p.TaskStateID == 10 || p.TaskStateID == 11 || p.TaskStateID == 12)

C# lambdas don't use a subset of the C# language: they use the whole language. Everything possible in C# is available to lambdas. The only requirement is that the expression must return the right type; and even then you can use curly braces to encompass more complex code:

p => { /* code block that has a return statement here */ }

Upvotes: 1

Mark Byers
Mark Byers

Reputation: 838226

Use the conditional OR operator:

filteredTasks = filteredTasks.Where(p => p.TaskStateID == 10 ||
                                         p.TaskStateID == 11 ||
                                         p.TaskStateID == 12);

Upvotes: 8

Oded
Oded

Reputation: 499002

Use the OR (||) operator:

filteredTasks = filteredTasks.Where(p => p.TaskStateID == 10 || 
                                         p.TaskStateID == 11 || 
                                         p.TaskStateID == 12);

Upvotes: 56

Related Questions