Home > Back-end >  C# - How to Filter a List for condition A, then for these matched only, Filter by Condition B, witho
C# - How to Filter a List for condition A, then for these matched only, Filter by Condition B, witho

Time:09-21

I have a list of items:

Order - not return from DB Status Flag
1 Complete 0
2 Complete 1
3 Not Started 0
4 Complete 1

Expect Output:

Order - not return from DB Status Flag
2 Complete 1
3 Not Started 0
4 Complete 1

So Only for Item with Status == "Complete", then filter with Flag == 1. For other Status which are not "Complete", do nothing.

I can:

var notCompletedItems = todoList.Where(item => item.Status != "Complete");
var filtedCompletedItem  = todoList.Where(item => item.Status == "Complete" && Flag);
var finalResult = notCompletedItems.AddRange(filtedCompletedItem);

Note The Order won't return from DB, only to explain the question purpose. How to exactly return the Expect Output. and Also optimize the code...

Thanks in advance!

CodePudding user response:

You can accomplish this with only one line of code so that you don't have to generate multiple lists. Try this out:

var finalResult = todoList.Where(item => item.Status != "Complete" || (item.Status == "Complete" && item.Flag == 1);
  • Related