Reputation: 940
What I have
I have a list, which would execute only when certain conditions are met
var list = data.Where(!t.Area.HasValue || t => t.Area == response.Area).Select(t => new Status()
{
PK = t.PK,
Area = t.Area,
Description = t.Description
//other stuff
}).ToList();
What I want
This list works fine the way it is, but now I want to modify it slightly. For one of the variables, I want to run an if-else statement, and that variable will be the return result of if-else statement execution
var list = data.Where(!t.Area.HasValue || t => t.Area == response.Area).Select(t => new Status()
{
PK = t.PK,
Area = t.Area,
Description, //<---------------returns the value of executed if-else statement
//if (t.Area.HasValue) Description = a;
//else Description = b;
OtherStuff = t.OtherStuff
}).ToList();
My question is: Where to I place that if-else condition in order to properly execute it?
What I tried
I tried placing if-else statement inside the place of actual variable between two commas.
I tried using temp variable, whose result will be returned, but I don't want to have this temp variable in my list.
I tried having extra conditions inside Where() before I realized it is a set of conditions to actually execute that list.
Searching SO and internet did not get me desired outcomes to try out (hopefully, I was not just using a wrong search criteria).
Upvotes: 3
Views: 2594
Reputation: 103485
var list = data.Where(!t.Area.HasValue || t => t.Area == response.Area).Select(t => new Status()
{
PK = t.PK,
Area = t.Area,
Description = t.Area.HasValue ? a : b,
OtherStuff = t.OtherStuff
}).ToList();
Upvotes: 2
Reputation: 765
var list = data.Where(!t.Area.HasValue || t => t.Area == response.Area).Select(t => new Status()
{
PK = t.PK,
Area = t.Area,
Description = t.Area.HasValue ? a : b
//other stuff
}).ToList();
Upvotes: 1
Reputation: 62488
You can use ternary operator for it following way :
Area = t.Area,
Description = t.Area.HasValue ? a : b,
Upvotes: 2