0

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

4 回答 4

4

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

var result = stringList.Where(s => !string.IsNullOrWhiteSpace(s)).ToArray();
于 2015-03-11T01:24:01.463 回答
3

无子函数

您可以在没有子函数的情况下执行此操作的最短方法如下:

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

带子功能

但是,我建议使用您的子功能:

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

扩展方法

或者,如果您真的在寻找其他选项......您可以创建一个扩展方法:

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

    return list;
}

然后像这样使用它:

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

稍后添加其他项目:

list.AddIfNotEmpty("new item", string.Empty);
于 2015-03-11T02:00:14.797 回答
0
private List<string> GetUniqueKeys(params string[] list)
{
    var newList = new List<string>();
    newList.AddRange(list.Where(str => !string.IsNullOrEmpty(str)));

    return newList;
}
于 2015-03-11T01:23:11.747 回答
0

使用子方法..

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

没有子方法..

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();

我建议将子方法与params.

于 2015-03-11T02:12:43.707 回答