HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpMajor

Checking for Null before adding into List

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
nullintocheckingaddingforbeforelist

Problem

Is there any way to refactor this?

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

            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; }
}

Solution

This is a bit neater:

List ListOption = new List { };
Action 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();

Code Snippets

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;
return (new string[] {Option1, Option2, Option3, Option4})
       .Where(x => !String.IsNullOrEmpty(x))
       .Select(x => new Option { Name = x })
       .ToList();

Context

StackExchange Code Review Q#3290, answer score: 34

Revisions (0)

No revisions yet.