KeentoLearn
KeentoLearn

Reputation: 355

Remove leading and trailing whitespace from list of string in C#

I have list of string and I want to trim leading and trailing whitespace.

It holds value like " Hi this ", " computer " and so on.

Can anyone please suggest me how to do this?

List<string> aList = new List<string>();

Upvotes: 1

Views: 3063

Answers (5)

OO7
OO7

Reputation: 690

Well, bellow is the simple answer:

var xList = aList.Select(x => x?.Trim('"').Trim()).ToList();

It will remove leading and trailing whitespace inside quotes.

Upvotes: 0

Prateek Shrivastava
Prateek Shrivastava

Reputation: 1937

aList = aList.Select(x => x.Trim()).ToList();

Upvotes: 1

D Stanley
D Stanley

Reputation: 152521

Pretty simple with Linq:

var newList = aList.Select(s => s.Trim());

If you need a list just add .ToList() to the end. You could also overwrite the same list variable, or use a for loop to replace the strings in the list in-place:

for(int i=0; i < aList.Count; i++)
{
    aList[i] = aList[i].Trim();
}

Upvotes: 3

jaspenlind
jaspenlind

Reputation: 369

You can trim leading and trailing whitespace on each item by using a Linq selector:

var withoutWhitespace = aList.Select(item => item.Trim()).ToList();

Upvotes: 5

Lews Therin
Lews Therin

Reputation: 10995

aList.Select(x=>x.TrimStart().TrimEnd()).ToList()

Upvotes: 2

Related Questions