2

I am looking for a convenient way to drop list items with empty string as their value.

I know I could check each string to see if it is empty before loading into the list.

List<string> items = new List<string>();
if (!string.IsNullOrEmpty(someString))
{
    items.Add(someString);
}

However, this seems a bit cumbersome especially if I have a lot of strings to add to the list.

Alternatively, I could just load all the strings regardless of being empty or not:

List<string> items = new List<string>();
items.Add("one");
items.Add("");
items.Add("two")

Then iterate over the list and if an empty string is found remove it.

foreach (string item in items)
{
    if (string.IsNullOrEmpty(item))
    {
        items.Remove(item);
    }              
}

Are these my only two options, perhaps there is something in Linq?

Thanks for any help with this.

4

3 回答 3

7

尝试:

 items.RemoveAll(s => string.IsNullOrEmpty(s));

或者您可以使用以下方法过滤掉它们where

var noEmptyStrings = items.Where(s => !string.IsNullOrEmpty(s));
于 2013-05-03T13:20:39.350 回答
1

作为 Darren 答案的扩展,您可以使用扩展方法:

    /// <summary>
    /// Returns the provided collection of strings without any empty strings.
    /// </summary>
    /// <param name="items">The collection to filter</param>
    /// <returns>The collection without any empty strings.</returns>
    public static IEnumerable<string> RemoveEmpty(this IEnumerable<string> items)
    {
        return items.Where(i => !String.IsNullOrEmpty(i));
    }

然后用法:

        List<string> items = new List<string>();
        items.Add("Foo");
        items.Add("");
        items.Add("Bar");

        var nonEmpty = items.RemoveEmpty();
于 2013-05-03T13:30:46.200 回答
1

在将字符串添加到您的列表之前检查它们总是比从列表中删除它们或创建一个全新的字符串更容易。您正在尝试避免字符串比较(实际上检查其是否为空,执行速度非常快)并通过列表复制替换它,这将对您的应用程序的性能产生很大影响。如果您只能在将字符串添加到列表之前检查字符串 - 这样做,不要复合。

于 2013-05-03T13:33:39.277 回答