What is the most concise way to array a series of string variables that may be empty

462 views Asked by At

I need to array an ad-hoc set of strings like this

string a = null;
string b = "include me";
string c = string.Empty;
string d = "me too!";

without including null or empty strings. I know I can use a child function and params:

private List<string> GetUniqueKeys(params string[] list)
{
    var newList = new List<string>();
    foreach (string s in list)
    {
        if (!string.IsNullOrWhiteSpace(s))
            newList.Add(s);
    }
    return newList;
}

///

return this.GetUniqueKeys(a, b, c, d).ToArray();

but is there any simpler way to do this that I'm not seeing?

EDIT: Sorry about that, happy to vote up the first LINQer, but I should have specified that I was trying to get rid of the child method altogether, not simplify it.

4

There are 4 answers

0
David Sherret On BEST ANSWER

No Child Function

The shortest way you can do this without a child function is the following:

var a = new string[] { a, b, c, d }.Where(s => !string.IsNullOrWhiteSpace(s));

With Child Function

However, I would recommend using your child function:

private IEnumerable<string> GetUniqueKeys(params string[] list)
{
    return list.Where(s => !string.IsNullOrWhitespace(s));
}

Extension Method

Alternatively, if you're really looking for other options... you could create an extension method:

public static List<string> AddIfNotEmpty(this List<string> list, params string[] items)
{
    list.AddRange(items.Where(s => !string.IsNullOrEmpty(s)));

    return list;
}

Then use it like such:

var list = new List<string>().AddIfNotEmpty(a, b, c, d);

And add other items later:

list.AddIfNotEmpty("new item", string.Empty);
0
ro-E On
private List<string> GetUniqueKeys(params string[] list)
{
    var newList = new List<string>();
    newList.AddRange(list.Where(str => !string.IsNullOrEmpty(str)));

    return newList;
}
4
lincoln On

If the input strings are enumerable, you can use linq.

var result = stringList.Where(s => !string.IsNullOrWhiteSpace(s)).ToArray();
0
Magic Mick On

With Child method..

private List<string> GetUniqueKeys(params string[] list)
{
    return list.Where(x => !string.IsNullOrWhiteSpace(x)).ToList();
}

Without Child method..

string a = null;
string b = "include me";
string c = string.Empty;
string d = "me too!";

string[] lst = { a, b, c, d };
var uniqueLst = lst.Where(x => !string.IsNullOrWhiteSpace(x)).ToList(); //Or ToArray();

I recommend to use child method with params.