LINQ版本的循环数组并执行多种类型的替换

时间:2016-06-06 21:50:49

标签: c# linq

我有一个名为currentRow的字符串数组。我有一个看起来像这样的循环:

for (int index = 0; index < currentRow.Length; index++)
{
    if (currentRow[index] == string.Empty)
    {
        currentRow[index] = null;
    }

    if (currentRow[index] == "''")
    {
        currentRow[index] = string.Empty;
    }
}

如果我将其作为LINQ查询来做,那会是什么样子?我最好使用循环代替吗?看起来像LINQ查询我必须创建数组的多个副本。

2 个答案:

答案 0 :(得分:1)

您需要投影,而不是选择。

记住LINQ是为查询而不是实际更新现有值而设置的。

如果您想要执行您所指示的内容,您可以使用LINQ创建现有集合的投影,通过Select()声明将您的值映射到其他人:

// This would project each element from your currentRow array and set its value to
// either null (if it was empty), the empty string (if it was just single quotes) or
// use its original value.
var output = currentRow.Select(x => x == "" ? null : x == "''" ? "" : x).ToArray();

循环会是更好的选择吗?

您当前的方法没有任何问题。它不需要创建一个完全独立的数组来存储您的新值(通过投影)。我知道它看起来可能不像LINQ语句那样简洁,它仍然可以工作并且非常易读(与某些LINQ查询不同)。

答案 1 :(得分:1)

  

如果我将其作为LINQ查询来做,那会是什么样的?

如果您想投影到 new 数组(并且可选择覆盖现有引用),它将如下所示:

currentRow.Select(r => r == string.Empty ? null : 
                       r == "''" ? string.Empty : r)
          .ToArray();

如果您想使用Linq来修改原始集合,它看起来就像一个邪恶的lambda,副作用太难以在这个地方说出来。

  

我最好还是使用循环吗?

可能。您可以避免创建新阵列。

  

看起来像LINQ查询我必须创建数组的多个副本。

不,只需另外一份。如果你覆盖原始引用(如果没有别的引用它),它将根据需要收集垃圾。

相关问题