我想有机会回答这个问题,只是为了强调我们何时应该使用linq和经典的for循环。
不幸的是,今天人们并不太关心性能,因为我们已经习惯在非常强大的计算机上工作。无论如何,只需尝试下面的代码,您就会发现Linq比经典的for版本慢100倍以上。只有当您需要编写的表达式真正复杂且希望使其更易读时,才应使用Linq。
我没有花时间研究下面展示的解决方案,因为我想专注于性能。
public static void Main(string [] arg)
{
List<List<string>> listOfList = new List<List<string>>()
{
new List<string>()
{
"1.1","2.2"
}
,
new List<string>()
{
"2.1","2.2","2.3"
}
};
Stopwatch stopwatch=new Stopwatch();
stopwatch.Start();
int totalUsingLinq = listOfList.Sum(x => x.Count);
stopwatch.Stop();
Console.WriteLine("Using Linq:{0}",stopwatch.Elapsed);
int totalUsingFor = 0;
stopwatch.Reset();
stopwatch.Start();
totalUsingFor = 0;
for(int i=0;i<listOfList.Count;i++)
{
var mainItem = listOfList[i];
if(mainItem!=null)
{
totalUsingFor += mainItem.Count;
}
}
stopwatch.Stop();
Console.WriteLine("Using for:{0}", stopwatch.Elapsed);
}
使用 for 进行去重(仅举例)。
在这种情况下,我创建了一个非常“瓶颈”的函数来执行此操作,但它仍然更快。
public class Program
{
public static void Main(string[] arg)
{
List<List<string>> listOfList = new List<List<string>>()
{
new List<string>()
{
"1.1","2.2","1.1","1.1","2.2","1.1","1.1","2.2","1.1","1.1"
}
,
new List<string>()
{
"2.1","2.2","2.3","2.3","1.1","2.2","1.1","1.1","2.2","1.1","1.1","2.2","1.1","1.1","2.2","1.1","1.1","2.2","1.1"
}
};
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
int totalUsingLinq = listOfList.Sum(l => l.Distinct().Count());
stopwatch.Stop();
Console.WriteLine("Using Linq:{0}", stopwatch.Elapsed);
int totalUsingFor = 0;
stopwatch.Reset();
stopwatch.Start();
totalUsingFor = 0;
for (int i = 0; i < listOfList.Count; i++)
{
var mainItem = listOfList[i];
if (mainItem != null)
{
for(int y=0;y<mainItem.Count;y++)
{
if(mainItem[y]!=null)
{
totalUsingFor++;
NullDuplicateItems(y, ref mainItem);
}
}
}
}
stopwatch.Stop();
Console.WriteLine("Using for:{0}", stopwatch.Elapsed);
}
public static void NullDuplicateItems(int index,ref List<string > list)
{
var item = list[index];
for(int i=index+1;i<list.Count;i++)
{
if(list[i]==item)
{
list[i] = null;
}
}
}
}
.ToList()
,可以使用Count()
扩展方法。 - Homam