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 O开发者_开发问答R 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
Use the OR
(||) operator:
filteredTasks = filteredTasks.Where(p => p.TaskStateID == 10 ||
p.TaskStateID == 11 ||
p.TaskStateID == 12);
var taskIds = new[]{10, 11, 12}
var selectedTasks = filteredTasks.Where(p => taskIds.Contains(p.TaskStateID))
Use the conditional OR operator:
filteredTasks = filteredTasks.Where(p => p.TaskStateID == 10 ||
p.TaskStateID == 11 ||
p.TaskStateID == 12);
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);
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 */ }
filteredTasks.Where(p => (p.TaskStateID == 10 || p.TaskStateID == 11 || p.TaskStateID == 12))
精彩评论