如果声明简短

时间:2014-02-04 01:25:58

标签: c# if-statement

如果有更简洁的方式来编写这种类型的陈述:

if (!string.IsNullOrEmpty(c1))
{
    var _individual = new Individual { Age = Convert.ToInt32(c1) };
    request.Individuals.Add(_individual);
}

if (!string.IsNullOrEmpty(c2))
{
    var _individual = new Individual { Age = Convert.ToInt32(c2) };
    request.Individuals.Add(_individual);
}

if (!string.IsNullOrEmpty(c3))
{
    var _individual = new Individual { Age = Convert.ToInt32(c3) };
    request.Individuals.Add(_individual);
}

if (!string.IsNullOrEmpty(c4))
{
    var _individual = new Individual { Age = Convert.ToInt32(c4) };
    request.Individuals.Add(_individual);
}

if (!string.IsNullOrEmpty(c5))
{
    var _individual = new Individual { Age = Convert.ToInt32(c5) };
    request.Individuals.Add(_individual);
}

3 个答案:

答案 0 :(得分:10)

当然!写一个方法:

private void AddIfAgeValid(string age) 
{    
    if (!string.IsNullOrEmpty(age))
    {
        var _individual = new Individual { Age = Convert.ToInt32(age) };
        request.Individuals.Add(_individual);
    }
}

然后打电话给它:

AddIfAgeValid(c1);
AddIfAgeValid(c2);
AddIfAgeValid(c3);
// ..

您可能还必须传递request,不确定您声明的位置。

您可能还希望使用数组或List<string>来存储您的年龄,而不是c1, c2, c3, ..变量。

答案 1 :(得分:7)

foreach (var c in new[] {c1, c2, c3, c4, c5})
{
  if (!string.IsNullOrEmpty(c))
  {
    var _individual = new Individual { Age = Convert.ToInt32(c) };
    request.Individuals.Add(_individual);
  }
}

答案 2 :(得分:7)

foreach (var x in (new[] { c1, c2, c3, c4, c5 }).Where(x => !string.IsNullOrEmpty(x)))
    request.Individuals.Add(new Individual { Age = Convert.ToInt32(x) });

或单行,如果只有Individuals支持AddRange

request.Individuals.AddRange((new[] { c1, c2, c3, c4, c5 }).Where(x => !string.IsNullOrEmpty(x)).Select(x => new Individual { Age = Convert.ToInt32(x) }));

但我不会那么远。它的可读性远低于foreach