我正在尝试删除?从使用TrimEnd
的列表中单词的末尾开始,如果有比TrimEnd
更好的方法,我将采用它。
我已经尝试过Trim
和Remove
。该列表是.Split(' ')
的字符串,以“?”结尾连接到最后一个单词。
public static List<String> CleanThing(List<string> dirtyList)
{
List<string> cleanList = new List<string>();
// cleanList =
/* dirtyList.ForEach(delegate(string e)
e = e.TrimEnd('?')
=*/
Console.WriteLine("\nThe # of Removals is: " + dirtyList.RemoveAll(x => x == "What" || x == "?" || x == "is") + "\n");
dirtyList.ForEach(delegate(string e){
e = e.TrimEnd('?');
Console.WriteLine(e);
});
cleanList = dirtyList;
return cleanList;
}
}
返回的列表具有“两个?”但是Console.WriteLine(e)
显示“两个”
答案 0 :(得分:1)
您要重新分配e变量,这将创建一个新对象e = e.TrimEnd('?')
,您将不会更新列表中的那个,因为它仍然指向旧参考,
相反,只需在清除列表中选择所需内容即可
cleanList = dirtyList.Select(x => x.TrimEnd('?')).ToList()
答案 1 :(得分:1)
我在这里看到了一些LINQ解决方案。
如果您想使用非LINQ解决方案,则一种方法可能是使用for
循环:
for (int i = 0; i < dirtyList.Count; i++) {
dirtyList[i] = dirtyList[i].TrimEnd('?');
}
这会遍历List
中的每个元素,并用TrimEnd
替换现有的值。
或者,如果要将清除的值直接添加到cleanList
:
for (int i = 0; i < dirtyList.Count; i++) {
cleanList.Add(dirtyList[i].TrimEnd('?'));
}
如果直接添加到cleanList
,您也可以使用foreach
:
foreach (string item in dirtyList) {
cleanList.Add(item.TrimEnd('?'));
}
答案 2 :(得分:0)
trimed = mylist.Select(s => s.TrimEnd('.')).ToList()