我想替换List<string>
中的所有空值,但是如果不想进行foreach循环。
List<string> tmpList = new List<string>();
//src is a List<string> where I want to remplace the null by "NULL"
foreach(string s in src)
{
if(s == null)
{
tmpList.Add("NULL");
}
else
{
tmpList.Add(s);
}
}
src = tmpList;
你知道更好的方法吗? LINQ可能是?
答案 0 :(得分:10)
src.Select(s => s ?? "NULL").ToList();
但使用foreach循环有什么问题?
答案 1 :(得分:1)
var list = new List<string>() { null, "test1", "test2" };
for (int i = 0; i < list.Count; i++)
{
if (list[i] == null)
{
list[i] = "NULL";
}
}
否foreach
。
编辑:
由于似乎没有人理解这个答案的含义:LINQ在内部进行foreach
循环。您想有条件地修改列表中的每个项目?然后你必须枚举它。
LINQ可以帮助我们编写查询。 哦等等,这是LINQ的Q 。
LINQ不在此修改现有列表。在这里使用一个好的旧for loop
。您当然可以根据具有修改值的现有列表创建新列表(请参阅最佳投票答案),但我担心您将以错误的方式开始使用LINQ。