bpeikes
bpeikes

Reputation: 3705

Using lambdas in C# to perform multiple functions on an array

I have a string which I would like to split on a particular delimiter and then remove starting and trailing whitespace from each member. Currently the code looks like:

string s = "A, B, C ,D";
string[] parts = s.Split(',');
for(int i = 0; i++; i< parts.Length)
{
     parts[i] = parts[i].Trim();
}

I feel like there should be a way to do this with lambdas, so that it could fit on one line, but I can't wrap my head around it. I'd rather stay away from LINQ, but I'm not against it as a solution either.

string s = "A, B, C ,D";
string[] parts = s.Split(','); // This line should be able to perform the trims as well

I've been working in Python recently and I think that's what has made me revisit how I think about solutions to problems in C#.

Upvotes: 1

Views: 244

Answers (3)

Michael Edenfield
Michael Edenfield

Reputation: 28338

If you really want to avoid LINQ, you can split on multiple characters and discard the extra "empty" entries you get between the "," and spaces. Note that you can end up getting odd results (e.g. if you have consecutive "," delimiters you won't get the empty string in between them anymore):

s.Split(new char[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries);

This will work for your sample input, but its very fragile. For example, as @Oscar points out, whitespace inside your tokens will cause them to get split as well. I'd highly recommend you go with one of the LINQ-based options instead.

Upvotes: 1

Servy
Servy

Reputation: 203827

var parts = s.Split(',').Select(part => part.Trim());

Upvotes: 4

Oscar Mederos
Oscar Mederos

Reputation: 29863

What about:

string[] parts = s.Split(',').Select(x => x.Trim()).ToArray();

Upvotes: 8

Related Questions