user2945722
user2945722

Reputation: 1313

Reduce code bloat when trimming an array of strings

I have a string of comma separated values, to get a string array from this I use

string[] values = value.Split(',');

I want to trim all these values by creating a new list of string and calling a foreach on the array like this

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

 foreach (string str in values)
     trimmedValues.Add(str.Trim());

Is there a more efficent way to do this with less code say by calling a method on the array itself?

Upvotes: 1

Views: 73

Answers (3)

user3041160
user3041160

Reputation: 684

Try this :

var myTrimResult = "a ,b , c ".Split(',').Select(x => x.Trim());

The "myTrimResult" variable will contain trimmed elements.

Upvotes: 1

LittleSweetSeas
LittleSweetSeas

Reputation: 7054

To effectively reduce code bloat, I suggest to use an extension.

Declare a method like the following, in a common context in your project (or even better, in an external helper DLL to carry among different projects):

public static List<string> TrimList(this string[] array)
{
    var list = new List<string>();
    foreach (var s in array)
    {
        list.Add(s.Trim());
    }
    return list;
}

Now, in your code, you can simply use:

var trimmedValues = values.TrimList();

I find it more readable than using LINQ expression in code

Upvotes: 0

vborutenko
vborutenko

Reputation: 4443

Use linq

List<string> trimmedValues = values.Select(v => v.trim()).toList()

Upvotes: 4

Related Questions