Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IF statement inside a LINQ SELECT

Tags:

I'm trying to produce an IF conditional statement inside of a "select new" that checks the values of two fields in order to fill a property.

from e in Employees where e.EmployeeID == id select new {     EmployeeID = e.EmployeeID,     EmployeeName = e.FirstName + " " + e.LastName,     Status = (if e.col1.HasValue then "This Value" else if e.col2.HasValue then "Other Value") } 

The columns are nullable and therefore the column types are DateTime? data types.

Only one or the other column will have a datetime value, not both.

How do I go about doing this???

like image 550
kntcnrg Avatar asked Jun 23 '09 00:06

kntcnrg


People also ask

How do I select a query in Linq?

LINQ query syntax always ends with a Select or Group clause. The Select clause is used to shape the data. You can select the whole object as it is or only some properties of it. In the above example, we selected the each resulted string elements.


2 Answers

Status = e.col1.HasValue ? "This Value" : (e.col2.HasValue ? "Other Value" : null) 
like image 165
mmx Avatar answered Sep 22 '22 23:09

mmx


use the null coelacing operator for this

Status = e.col1.HasValue ? e.col1.Value ?? "This Value" : e.col2.Value ?? "Other Value" 
like image 32
Rony Avatar answered Sep 22 '22 23:09

Rony