写了一个比较LINQ与常规方法,速度的代码,如下using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
//- 此程序用来比较常规方法和LINQ查询各自的速度-------结论是相差不大----排除类型推断可能相差无几....namespace _001
{
class startup
{
static void Main(string[] args)
{
Person [] people = {
new Person("YM",21),
new Person("DJ",19),
new Person("OMG",30),
new Person("TA",25),
};
long RoundSum = 100;
long StartTime = 0;
long EndTime = 0;
StartTime = Environment.TickCount;
for (int i = 0;i<RoundSum ; i++)
{
foreach(Person p in people)
{
if (p.age >=26)
{
Console.WriteLine(p.name);
}
}
}
EndTime = Environment.TickCount;
Console.WriteLine("the traditional method cost {0}",EndTime - StartTime);
Console.ReadKey(); StartTime = Environment.TickCount;
for (int i = 0;i<RoundSum;i++)
{
var ageQuery=from p in people
where p.age>=26
select p;
foreach (Person p in ageQuery)
{
Console.WriteLine(p.name);
}
}
EndTime = Environment.TickCount;
Console.WriteLine("the LINQ method cost {0}", EndTime - StartTime);
Console.ReadKey();
}
class Person
{
public string name = "";
public int age = 0;
public Person(string _name,int _age)
{
name = _name;
age = _age;
}
}
}
}重点在.
for (int i = 0;i<RoundSum;i++)
{
var ageQuery=from p in people
where p.age>=26
select p;
foreach (Person p in ageQuery)
{
Console.WriteLine(p.name);
}
}若此处不用var,那么因该写成什么,写成Person[]或者Person都会提示查询语句里面某部分类型无法隐式转换.
用.gettype方法看ageQuery的类型,结果返回很长一串 的 类型...
谢谢
using System.Collections.Generic;
using System.Linq;
using System.Text;
//- 此程序用来比较常规方法和LINQ查询各自的速度-------结论是相差不大----排除类型推断可能相差无几....namespace _001
{
class startup
{
static void Main(string[] args)
{
Person [] people = {
new Person("YM",21),
new Person("DJ",19),
new Person("OMG",30),
new Person("TA",25),
};
long RoundSum = 100;
long StartTime = 0;
long EndTime = 0;
StartTime = Environment.TickCount;
for (int i = 0;i<RoundSum ; i++)
{
foreach(Person p in people)
{
if (p.age >=26)
{
Console.WriteLine(p.name);
}
}
}
EndTime = Environment.TickCount;
Console.WriteLine("the traditional method cost {0}",EndTime - StartTime);
Console.ReadKey(); StartTime = Environment.TickCount;
for (int i = 0;i<RoundSum;i++)
{
var ageQuery=from p in people
where p.age>=26
select p;
foreach (Person p in ageQuery)
{
Console.WriteLine(p.name);
}
}
EndTime = Environment.TickCount;
Console.WriteLine("the LINQ method cost {0}", EndTime - StartTime);
Console.ReadKey();
}
class Person
{
public string name = "";
public int age = 0;
public Person(string _name,int _age)
{
name = _name;
age = _age;
}
}
}
}重点在.
for (int i = 0;i<RoundSum;i++)
{
var ageQuery=from p in people
where p.age>=26
select p;
foreach (Person p in ageQuery)
{
Console.WriteLine(p.name);
}
}若此处不用var,那么因该写成什么,写成Person[]或者Person都会提示查询语句里面某部分类型无法隐式转换.
用.gettype方法看ageQuery的类型,结果返回很长一串 的 类型...
谢谢
T[] arr = ().ToArray <T>();