简体   繁体   中英

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

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.

如果输入字符串可枚举,则可以使用linq。

var result = stringList.Where(s => !string.IsNullOrWhiteSpace(s)).ToArray();

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);
private List<string> GetUniqueKeys(params string[] list)
{
    var newList = new List<string>();
    newList.AddRange(list.Where(str => !string.IsNullOrEmpty(str)));

    return newList;
}

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM