Baxter
Baxter

Reputation: 5845

Convenient way to drop empty strings from a collection

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.

Upvotes: 2

Views: 2891

Answers (3)

Tarec
Tarec

Reputation: 3255

Checking strings before adding them to your list will always be less cumbersome than deleting them from the list or creating a whole new one. You're trying to avoid string comparison (checking its emptyness actually, which is executed really fast) and replace it by list copying, which will have a strong impact on your app's performance. If you only can check strings before adding them to list - do so, and don't compound.

Upvotes: 1

Paulie Waulie
Paulie Waulie

Reputation: 1690

As an extension to Darren's answer you could use an extension method :

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

And Then usage :

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

        var nonEmpty = items.RemoveEmpty();

Upvotes: 1

Darren
Darren

Reputation: 70814

Try:

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

Or you can filter them out using where:

var noEmptyStrings = items.Where(s => !string.IsNullOrEmpty(s));

Upvotes: 7

Related Questions