一、.LINQ查询
例如:
static void LINQQuery()
{
var query = from r in Formula1.GetChampions()
where r.Country == "Brazil"
orderby r.Wins descending
select r;
foreach (var r in query)
{
Console.WriteLine("{0:A}", r);
}
}
.扩展方法
扩展方法在静态类中声明,定义为一个静态方法。其中第一个参数定义了他扩展的类型,并且需要带this关键字。
IEnumerable类中存在扩展方法Where()、OrderbyDescending()和Select().这些方法都返回IEnumerable<TSource>.
例如:
static void ExtensionMethods()
{
var champions = new List<Racer>(Formula1.GetChampions());
IEnumerable<Racer> brazilChampions =
champions.Where(r => r.Country == "Brazil").
OrderByDescending(r => r.Wins).
Select(r => r);
foreach (Racer r in brazilChampions)
{
Console.WriteLine("{0:A}", r);
}
}
.推迟查询的执行
在运行期间定义查询表达式时,查询就不会运行。查询会在迭代数据项时运行。
.标准的查询操作符
)筛选:where 子句
static void Filtering()
{
var racers = from r in Formula1.GetChampions()
&& (r.Country == "Brazil" || r.Country == "Austria")
select r;
foreach (var r in racers)
{
Console.WriteLine("{0:A}", r);
}
}
)用索引筛选:在where()方法的重载中,可以传递第二个参数————索引。
例如返回姓氏以A开头、索引为偶数的赛手:
static void IndexFiltering()
{
var racers = Formula1.GetChampions().
Where((r, index) => r.LastName.StartsWith( != );
foreach (var r in racers)
{
Console.WriteLine("{0:A}", r);
}
}
)类型筛选:基于类型的筛选,可以使用OfType()扩展方法。
static void TypeFiltering()
{
, , };
var query = data.OfType<string>();
foreach (var s in query)
{
Console.WriteLine(s);
}
}
)复合的from子句
static void CompoundFrom()
{
var ferrariDrivers = from r in Formula1.GetChampions()
from c in r.Cars
where c == "Ferrari"
orderby r.LastName
select r.FirstName + " " + r.LastName;
foreach (var racer in ferrariDrivers)
{
Console.WriteLine(racer);
}
}
)分组
使用linq语法
static void Grouping()
{
var countries = from r in Formula1.GetChampions()
group r by r.Country into g
orderby g.Count() descending, g.Key
select new
{
Country = g.Key,
Count = g.Count()
};
foreach (var item in countries)
{
Console.WriteLine("{0, -10} {1}", item.Country, item.Count);
}
}
使用扩展方法
static void Grouping()
{
var countries = from r in Formula1.GetChampions()
group r by r.Country into g
orderby g.Count() descending, g.Key
select new
{
Country = g.Key,
Count = g.Count()
};
foreach (var item in countries)
{
Console.WriteLine("{0, -10} {1}", item.Country, item.Count);
}
}
.对嵌套的对象分组
static void GroupingWithNestedObjects()
{
var countries = from r in Formula1.GetChampions()
group r by r.Country into g
orderby g.Count() descending, g.Key
select new
{
Country = g.Key,
Count = g.Count(),
Racers = from r1 in g
orderby r1.LastName
select r1.FirstName + " " + r1.LastName
};
foreach (var item in countries)
{
Console.WriteLine("{0, -10} {1}", item.Country, item.Count);
foreach (var name in item.Racers)
{
Console.Write("{0}; ", name);
}
Console.WriteLine();
}
}
. 连接
static void Join()
{
var racers = from r in Formula1.GetChampions()
from y in r.Years
select new
{
Year = y,
Name = r.FirstName + " " + r.LastName
};
var teams = from t in
Formula1.GetContructorChampions()
from y in t.Years
select new
{
Year = y,
Name = t.Name
};
var racersAndTeams =
from r in racers
join t in teams on r.Year equals t.Year
select new
{
Year = r.Year,
Racer = r.Name,
Team = t.Name
};
Console.WriteLine("Year Champion " + "Constructor Title");
foreach (var item in racersAndTeams)
{
Console.WriteLine("{0}: {1,-20} {2}",
item.Year, item.Racer, item.Team);
}
}
.集合操作
扩展方法Distinctt()、Union()、Intersect()和Except()都是集合操作。
static void SetOperations()
{
Func<string, IEnumerable<Racer>> racersByCar =
car => from r in Formula1.GetChampions()
from c in r.Cars
where c == car
orderby r.LastName
select r;
Console.WriteLine("World champion with Ferrari and McLaren");
foreach (var racer in racersByCar("Ferrari").Intersect(racersByCar("McLaren")))
{
Console.WriteLine(racer);
}
}
.合并
Zip()方法,需要把第二个集合作为方法的第一个参数,第二个参数的类型时Func<TFirst,TSecond,TResult>。它通过参数first接收第一个集合的元素,通过参数second接收第二个集合的元素。
static void ZipOperation()
{
var racerNames = from r in Formula1.GetChampions()
where r.Country == "Italy"
orderby r.Wins descending
select new
{
Name = r.FirstName + " " + r.LastName
};
var racerNamesAndStarts = from r in Formula1.GetChampions()
where r.Country == "Italy"
orderby r.Wins descending
select new
{
LastName = r.LastName,
Starts = r.Starts
};
var racers = racerNames.Zip(racerNamesAndStarts, (first, second) => first.Name + ", starts: " + second.Starts);
foreach (var r in racers)
{
Console.WriteLine(r);
}
}
.分区
扩展方法Take()和Skip()等的分区操作可用于分页。
static void Partitioning()
{
;
int numberPages = (int)Math.Ceiling(Formula1.GetChampions().Count() /
(double)pageSize);
; page < numberPages; page++)
{
Console.WriteLine("Page {0}", page);
var racers =
(from r in Formula1.GetChampions()
orderby r.LastName
select r.FirstName + " " + r.LastName).
Skip(page * pageSize).Take(pageSize);
foreach (var name in racers)
{
Console.WriteLine(name);
}
Console.WriteLine();
}
}
.聚合操作符
如Count()、Sum()、Min()、Max()、Average()和Aggregate()不返回一个序列,而返回一个值。
例如sum()函数的用法:
static void Aggregate2()
{
var countries = (from c in
from r in Formula1.GetChampions()
group r by r.Country into c
select new
{
Country = c.Key,
Wins = (from r1 in c
select r1.Wins).Sum()
}
orderby c.Wins descending, c.Country
);
foreach (var country in countries)
{
Console.WriteLine("{0} {1}", country.Country, country.Wins);
}
}
.生成操作符
有时需要填充一个范围的数字,应使用Range()方法。这个方法把第一个参数作为起始值,第二个参数作为要填充的项数。
Empty()方法返回一个不返回值的迭代器,他可以用于一个集合的参数,可以跟参数传递空集合。
Repeate()方法返回一个迭代器,该迭代器吧同一个值重复特定的次数。
二、并行LINQ
.分区器:使用AsParallel()可以创建
static void IntroParallel()
{
;
var data = new int[arraySize];
var r = new Random();
; i < arraySize; i++)
{
data[i] = r.Next();
}
Stopwatch watch = new Stopwatch();
watch.Start();
var q1 = (from x in Partitioner.Create(data).AsParallel()
select x).Sum();
watch.Stop();
Console.WriteLine(watch.ElapsedMilliseconds);
}
.要取消长时间运行的查询,可以给查询添加WithCancellation()方法,并传递一个CancellationToken令牌作为参数。CancellationToken令牌cong CancellationTokenSource类中创建。
在主线程中调用CancellationTokenSource类的Cancel()方法可以取消任务。
static void Cancellation()
{
;
var data = new int[arraySize];
var r = new Random();
; i < arraySize; i++)
{
data[i] = r.Next();
}
var cts = new CancellationTokenSource();
new Thread(() =>
{
try
{
var sum = (from x in data.AsParallel().WithCancellation(cts.Token)
select x).Sum();
Console.WriteLine("query finished, sum: {0}", sum);
}
catch (OperationCanceledException ex)
{
Console.WriteLine(ex.Message);
}
}).Start();
Console.WriteLine("query started");
Console.Write("cancel? ");
int input = Console.Read();
if (input == 'Y' || input == 'y')
{
// cancel!
cts.Cancel();
}
}