Checking for Null before adding into List

  • Is there any way to refactor this?



    public IEnumerable<Option> Options
    {
    get
    {
    {
    List<Option> ListOption = new List<Option>();

    if (!String.IsNullOrEmpty(Option1))
    {
    ListOption.Add(new Option() {Name=Option1 });
    }
    if (!String.IsNullOrEmpty(Option2))
    {
    ListOption.Add(new Option() { Name = Option2 });
    }
    if (!String.IsNullOrEmpty(Option3))
    {
    ListOption.Add(new Option() { Name = Option3 });
    }
    if (!String.IsNullOrEmpty(Option4))
    {
    ListOption.Add(new Option() { Name = Option4 });
    }

    return ListOption;
    }
    }
    }

    public class Option
    {
    public string Name { get; set; }
    }

  • Rafe

    Rafe Correct answer

    10 years ago

    This is a bit neater:



    List<Option> ListOption = new List<Option> { };
    Action<string> add = x => { if (!String.IsNullOrEmpty(x)) ListOption.Add(new Option { Name = x }); }
    add(Option1);
    add(Option2);
    add(Option3);
    add(Option4);
    return ListOption;


    This is perhaps even better:



    return (new string[] {Option1, Option2, Option3, Option4})
    .Where(x => !String.IsNullOrEmpty(x))
    .Select(x => new Option { Name = x })
    .ToList();

    I personally find this hard to read and pretty long winded. I think a simple loop as per @Grant Thomas answer below might be more appropriate here.

License under CC-BY-SA with attribution


Content dated before 7/24/2021 11:53 AM

Tags used