5

我在 LINQPad 中尝试了以下代码并得到以下结果:

List<string> listFromSplit = new List<string>("a, b".Split(",".ToCharArray())).Dump();
listFromSplit.ForEach(delegate(string s) 
{ 
  s.Trim(); 
});
listFromSplit.Dump();

“a”和“b”

所以字母 b 没有像我预期的那样删除空格......?

有人有想法么

[注意:.Dump() 方法是 LINQPad 中的一个扩展方法,它以一种很好的智能格式化方式打印出任何对象的内容]

4

8 回答 8

17

你只是在创建一个修剪过的字符串,而不是给它分配任何东西。

var s = "  asd   ";
s.Trim();

不会更新s,而..

var s = "   asd   ";
s = s.Trim();

将要..

var listFromSplit = "a, b".Split(',').Select(s=>s.Trim());

我想,我会怎么做。

于 2008-10-15T16:03:06.697 回答
10

The String.Trim() method returns a string representing the updated string. It does not update the string object itself, but rather creates a new one.

You could do this:

s = s.Trim();

However you cannot update a collection while enumerating through it so you'd want to either fill a new List while enumerating over the existing one or populate the List manually using the string array returned by String.Split.

Filling a new list:

List<string> temp = new List<string>("a, b".Split(",".ToCharArray()));
List<string> listFromSplit = new List<string>();

temp.ForEach(delegate(string s) 
{ 
    listFromSplit.Add(s.Trim()); 
});

listFromSplit.Dump();

Populating Manually:

string[] temp = "a, b".Split(",".ToCharArray());
List<string> listFromSplit = new List<string>();

foreach (string s in temp)
{
    listFromSplit.Add(s.Trim()); 
};

listFromSplit.Dump();
于 2008-10-15T16:09:18.523 回答
4

Further to the answer posted by Adrian Kuhn you could do the following:

var result = listFromSplit.Select(s => s.Trim());
于 2009-02-25T01:12:24.833 回答
2

The string instances are immutable. Anything that seems to modify one, creates a new instance instead.

于 2008-10-15T16:06:16.347 回答
1

您没有将修剪后的结果分配给任何东西。这是一个典型的错误,我刚刚摆脱了用 string.Replace 犯这个错误的习惯 :)

于 2008-10-15T16:04:33.980 回答
1

I have no IDE up and running, but this should get the job done (unless I am wrong):

var result = from each in listFromSplit select each.Trim();
于 2008-10-15T16:53:51.930 回答
0

Split on both spaces and commas and remove any empty entries. All nice and trimmed. Assumes that your strings don't contain spaces, though.

List<string> listFromSplit =
     new List<string>( "a , b ".Split( new char[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries ));
于 2008-10-15T16:09:55.370 回答
0

The linq options others have provided should work well. As another option, here is an extension method using a for loop:

    public static void TrimCollection(this IList<string> stringCollection) {

        for (int i = 0; i <= stringCollection.Count() - 1; i++)
            stringCollection[i] = stringCollection[i].Trim();

    }
于 2012-08-10T14:57:55.577 回答