Reputation: 355
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
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
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
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