Reputation: 517
Hi all and thanks in advance, I'm stumped on how to use a where clause with the conditional statement that I need to execute. I have two grids of information, one grid is dependent on the other for determining what shows. In the first grid the Date field can be a date or it can say Never.
The first grid's data is like so:
ID Date Title
--- ----- ------
12 Never Home
13 Never School
14 Never Work
The second grid will only show one row of the three depending on what the value of the Date field is, in this example it should be:
ID Date Title
--- ----- ------
12 Never Home
This information is pulled into a List that I want to iterate through using LINQ. What I want to achieve is:
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();
Upvotes: 3
Views: 553
Reputation: 4203
Since you have two rules, you will need an if condition somewhere.
The simplest form that I can think of is something like this:
return myList.All(x => x.Date == "Never") ? myList.FirstOrDefault() : myList.FirstOrDefault(x => x.Date != "Never");
Upvotes: -1
Reputation: 54781
var record = myList.FirstOrDefault(m => !m.Date.Equals("Never"))
?? myList.FirstOrDefault();
i.e. first one that doesn't equal never or null, and if null, just the first one (or null).
Upvotes: 8
Reputation: 16137
You're 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 on .All()
just look at this MSDN post.
Upvotes: 7