Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simplest Way to Trim All String within a List<string[]> using LINQ?

Tags:

c#

linq

I have a List <string[]>.

What is the simplest way to trim all strings using LINQ?

like image 860
alansiqueira27 Avatar asked Feb 09 '15 18:02

alansiqueira27


2 Answers

LINQ is for querying, It shouldn't be used for modifying existing collection. You can use the following, but it will return a new collection.

List<string[]> newList = list.Select(outer => outer
                .Select(innerItem => innerItem.Trim())
                .ToArray())
                .ToList();

You may add checking against Null for each element in the string array before calling Trim to avoid NRE. Something like:

.Select(innerItem => innerItem != null ? innerItem.Trim() : null)
like image 170
Habib Avatar answered Nov 15 '22 02:11

Habib


If the original signature is correct it should be

var result = original
    .Select( x=> 
        x.Select(y => y.Trim())
         .ToArray())
    .ToList();

where x is each array of Strings in the original list, and y is the member from the inner array.

like image 36
Steve Mitcham Avatar answered Nov 15 '22 02:11

Steve Mitcham