gorrch
gorrch

Reputation: 551

Putting if statement inside new instance of class

Is it possible to put somehow if statement inside new class body?

this.inventory.Items.Select(x=> new StandardItem
{
   ItemNumber = x.ItNo,
   if(isAltered){
      PartNumber = x.PaNo
   }else{
      PartNumber = x.PaReplacedNo
   }
}

Above code returns compilation error.

Upvotes: 3

Views: 1822

Answers (4)

Blake Thingstad
Blake Thingstad

Reputation: 1659

You can use a ternary operator...

this.inventory.Items.Select(x=> new StandardItem
{
    ItemNumber = x.ItNo,
    PartNumber = isAltered ? x.PaNo : x.PaReplacedNo
}

Upvotes: 4

DavidG
DavidG

Reputation: 118977

You can use the conditional operator instead:

this.inventory.Items.Select(x=> new StandardItem
{
   ItemNumber = x.ItNo,
   PartNumber = isAltered ? x.PaNo : x.PaReplacedNo
}

Upvotes: 5

Zoran Horvat
Zoran Horvat

Reputation: 11301

You can use ternary operator as an in-line if-else:

this.inventory.Items.Select(x=> new StandardItem
{
  ItemNumber = x.ItNo,
  PartNumber = isAltered ? x.PaNo : x.PaReplacedNo
}

Upvotes: 2

juharr
juharr

Reputation: 32276

You can use the conditional operator

PartNumber = isAltered ? x.PaNo : x.PaReplaceNo

Upvotes: 2

Related Questions