【发布时间】:2012-05-17 18:06:27
【问题描述】:
我最近发现了 LINQ,我发现使用它非常有趣。目前我有以下功能,我不确定它是否会更高效,毕竟产生相同的输出。
你能告诉我你对此的看法吗?
该函数以非常简单的方式简单地删除标点符号:
private static byte[] FilterText(byte[] arr)
{
List<byte> filteredBytes = new List<byte>();
int j = 0; //index for filteredArray
for (int i = 0; i < arr.Length; i++)
{
if ((arr[i] >= 65 && arr[i] <= 90) || (arr[i] >= 97 && arr[i] <= 122) || arr[i] == 10 || arr[i] == 13 || arr[i] == 32)
{
filteredBytes.Insert(j, arr[i]) ;
j++;
}
}
//return the filtered content of the buffer
return filteredBytes.ToArray();
}
LINQ 替代方案:
private static byte [] FilterText2(byte[] arr)
{
var x = from a in arr
where ((a >= 65 && a <= 90) || (a >= 97 && a <= 122) || a == 10 || a == 13 || a == 32)
select a;
return x.ToArray();
}
【问题讨论】:
-
你为什么有
j?只需使用Add而不是Insert,您就可以省去那个计数器。 -
您可能应该将
.Insert(j,部分替换为.Add(并完全删除j计数器。 -
是的,谢谢,我只是修改了代码,甚至没有安排!
-
另外,由于大多数字符会被保留,您应该将
new List<byte>()替换为new List<byte>(arr.Length)。这将避免在列表变大时重新创建列表的内部结构。 -
你不需要。传递给
List<T>(int)构造函数的参数仅指示容量(在不调整大小的情况下可以 容纳多少),而不是实际容纳多少。
标签: c# performance linq