简体   繁体   中英

C# return value inside linq list based on if statement

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).

You can use ternary operator for it following way :

Area = t.Area,
Description = t.Area.HasValue ? a : b, 
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();
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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM