Where is the clause with the if statement

Hello everyone and thanks in advance, I don't understand how to use a where clause with a conditional expression that I need to execute. I have two grids of information, one grid depends on the other to define what it shows. In the first grid, the Date field can be a date, or it can say Never.

The first grid data looks like this:

ID       Date     Title
---      -----    ------
12       Never    Home
13       Never    School
14       Never    Work

      

The second grid will only display one row out of three depending on what value the Date field has, in this example it should be:

ID       Date     Title
---      -----    ------
12       Never    Home 

      

This information is inserted into the list I want to execute using LINQ. I want to achieve:

If(All Date values == 'Never') 
    Then pull the first one (12)
else
    if(Date has value)
         then pull the first that has a date

myList.Where(??what goes here??).Select(t => t).FirstOrDefault(); 

      

+3


source to share


3 answers


You are probably looking for something like this:

var record = myList.All(m => m.Date.Equals("Never")) 
               ? myList.FirstOrDefault() 
               : myList.FirstOrDefault(m => !m.Date.Equals("Never"));

      



For more details .All()

just check out this MSDN post .

+7


source


var record = myList.FirstOrDefault(m => !m.Date.Equals("Never"))
               ?? myList.FirstOrDefault();

      



i.e. the first, which is never equal or null, and if null, then only the first (or null).

+8


source


Since you have two rules, you need an if condition.

The simplest form I can think of is something like this:

return myList.All(x => x.Date == "Never") ? myList.FirstOrDefault() : myList.FirstOrDefault(x => x.Date != "Never");

      

-1


source







All Articles