BlowFish BlowFish - 2 days ago 4
C# Question

If/Then in Linq statement

In very simple terms I want to assign a string to a variable in a certain circumstance. I've tried to put the if then statement on the outside of the linq statement in a global variable but then it runs through the if/then assigns the string to variable and then prints it out for each row in my excel file that is being produced.

So how do i put a statement similar to this

var status = "";
if(_db.Owners.Select(i => i.Item1) != null && _db.Owners.Select(i => i.Item2) == null)
{
status = "S";
}


to my linq statement that looks similar to this

return _db.Owners
.Select(owner => new
{
CustomerId = owner.Report.CustomerId,
IdType = status,//I want this statement to print that status S only where the statement is true
}

Answer

I assume √ĆdType is a string, which you want empty if the statement is false. In that case, you can use this:

return _db.Owners
     .Select(owner => new
         {
             CustomerId = owner.Report.CustomerId,
             IdType = (owner.Item1 != null && owner.Item2 == null) ? "S": string.Empty, 
    }

UPDATE If you want to add a second case, you can do this:

return _db.Owners
     .Select(owner => new
         {
             CustomerId = owner.Report.CustomerId,
             IdType = (owner.Item1 != null && owner.Item2 == null) 
                     ? "S" : ([second case condition] ? [value] : string.Empty), 
    }
Comments