Bruno Rigoni
Bruno Rigoni

Reputation: 45

short if then else statements trouble

Hello I would like to shorten the code I write below. Can you help me?

IstSAF = 
    Convert.ToInt32(sD.FirstOrDefault(x => x.Decode == "IstSAF")?.Value) == 0 
        ? 1 
        : Convert.ToInt32(sD.FirstOrDefault(x => x.Decode == "IstSAF")?.Value);

Thank you

Edit:

Thanks for the replies. But I forgot to tell you that the code is inside an initialization of a class which in turn is inside a LINQ query.

IEnumerable<T>types = 
  From t in someTypes
  select new T()
  {
    IstSAF = 
      Convert.ToInt32(t.FirstOrDefault(x => x.Decode == "IstSAF")?.Valore) == 0 
          ? 1 
          : Convert.ToInt32(t.FirstOrDefault(x => x.Decode == "IstSAF")?.Valore),
  }

Upvotes: 0

Views: 84

Answers (3)

Michael Steinecke
Michael Steinecke

Reputation: 41

You can declare a variable in a Linq query:

    IEnumerable<T> types =
                from t in someTypes
                let valore = Convert.ToInt32(t.FirstOrDefault(x => x.Decode == "IstSAF")?.Valore)
                select new T()
                {
                    IstSAF = valore == 0 ? 1 : valore,
                };

Upvotes: 1

Prasad Telkikar
Prasad Telkikar

Reputation: 16079

You can try int.TryParse()

var myValue = sD.FirstOrDefault(x => x.Decode == "IstSAF")?.Value;
if(int.TryParse(myValue, out int IstSAF))
    IstSAF = IstSAF == 0 ? 1 : IstSAF;

As per your latest update:

If this is inside Linq Select(), then I would prefer to write foreach loop.

List<int> result = new List<int>();
foreach(var t in someTypes)
{
   //Logic to parse value to int
   var myValue = t.FirstOrDefault(x => x.Decode == "IstSAF")?.Value;
   if(int.TryParse(myValue, out int IstSAF))
       IstSAF = IstSAF == 0 ? 1 : IstSAF;

   result.Add(IstSAF); //Store int value.
}

//Print if you want
Console.WriteLine(string.Join(", ", result);

Upvotes: 1

Kjartan
Kjartan

Reputation: 19151

Just extract the messy part:

var myValue = Convert.ToInt32(sD.FirstOrDefault(x => x.Decode == "IstSAF")?.Value);

int IstSAF = myValue?.Value == 0 ? 1 : myValue?.Value;

...alternatively, for extra safety, use TryParse() and handle the result in some appropriate way:

int myValue;
bool isValid = int.TryParse(sD.FirstOrDefault(x => x.Decode == "IstSAF")?.Value, 
                            out myValue);

if(isValid)
{
    IstSAF = myValue.Value == 0 ? 1 : myValue.Value;
}
else
{
    throw new Exception("IstSAF was not a valid int value");
}

Upvotes: 4

Related Questions