42

I have this:

List<string> s = new List<string>{"", "a", "", "b", "", "c"};

I want to remove all the empty elements ("") from it quickly (probably through LINQ) without using a foreach statement because that makes the code look ugly.

2

4 Answers 4

67

You can use List.RemoveAll:

C#

s.RemoveAll(str => String.IsNullOrEmpty(str));

VB.NET

s.RemoveAll(Function(str) String.IsNullOrEmpty(str))
Sign up to request clarification or add additional context in comments.

4 Comments

I would simply write s.RemoveAll(String.IsNullOrEmpty);, you don't need a lambda in this case.
@PaoloMoretti: +1 Good point. But at least in VB.NET it isn't really shorter: s.RemoveAll(AddressOf String.IsNullOrEmpty) and the lamdba shows that it's possible to modify it easily. Imho it's more readable with the lambda.
Why is it returning number of removed elements instead of cleared list? This int count = s.RemoveAll(string.IsNullOrEmpty); is valid but List<string> list = s.RemoveAll(string.IsNullOrEmpty); not.
Because creating a new list with the removed elements would be a much more expensive operation than simply returning the count of removed elements. Note that the method should only remove elements and the return value is just an information that can be provided because it's already available. If you need to get a list of matching elements have a look at List.FindAll.
14

Check out with List.RemoveAll with String.IsNullOrEmpty() method;

Indicates whether the specified string is null or an Empty string.

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

Here is a DEMO.

Comments

11
s = s.Where(val => !string.IsNullOrEmpty(val)).ToList();

2 Comments

This is not correct should be s = s.Where(val => !string.IsNullOrEmpty(val)).ToList(); his Initial type is List<string> so you need to make sure it stays a List<string>
this way probably works IList. IList does not have RemoveAll.
0

I write below code to remove the blank value

List<string> s = new List<string>{"", "a", "", "b", "", "c"};
s = s.Where(t => !string.IsNullOrWhiteSpace(t)).Distinct().ToList();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.