In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-06 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)05/31 Report--
This article mainly introduces the relevant knowledge of "how to use LINQ in c #". The editor shows you the operation process through an actual case. The operation method is simple, fast and practical. I hope this article "how to use LINQ in c #" can help you solve the problem.
one。 Parallel LINQ
The class ParallelEnumerable contained in the System.Linq namespace can break down the work of the query and distribute it across multiple threads.
Although the Enumerable class defines extension methods for the IEnumerable interface, most of the extension methods of the ParallelEnumerable class are extensions of the ParallerQuery class. For example, the AsParallel () method extends the IEnumerable interface to return the ParallelQuery class, so normal collection classes can be queried in parallel.
1. Parallel query
The following demonstrates parallel LINQ (Parallel LINQ,PLINQ):
/ / populate a large int collection / / Enumerable.Range (0, arraySize) with random values to generate an empty sequence of integers in the specified range. / / Select (x = > r.Next (140), populate the set static IEnumerable SampleData () {const int arraySize = 100000000; var r = new Random (); return Enumerable.Range (0, arraySize) .Select (x = > r.Next (140)). ToList ();} static void IntroParallel () {var data = SampleData () Var watch = new Stopwatch (); / / non-parallel LINQ watch.Start (); var Q1 = (from x in data where Math.Log (x)
< 4 select x).Average(); watch.Stop(); Console.WriteLine("sync {0}, result: {1}", watch.ElapsedMilliseconds, q1); watch.Reset(); //使用data.AsParallel()进行并行LINQ watch.Start(); var q2 = (from x in data.AsParallel() where Math.Log(x) < 4 select x).Average(); watch.Stop(); Console.WriteLine("async {0}, result: {1}", watch.ElapsedMilliseconds, q2); } 输出;It is found that the parallel query time is used less, and the CPU utilization reaches 100% in the parallel query.
Like the LINQ query in LINQ Foundation II (https://www.yisu.com/article/244215.htm), the compiler modifies the syntax to call the AsParallel,Where (), Select (), Average () methods:
Var Q2 = data.AsParallel () .Where (x = > Math.Log (x) x) .Average ()
The AsParallel () method is defined with the ParallerEnumerable class to extend the IEnumerable interface, so it can be called on a simple array. The AsParallel () method returns ParallerQuery. Because of the type returned, the Where () method chosen by the compiler is ParallerEnumerable.Where () instead of Enumerable.Where ().
For the PrarllelEnumerable class, the query is partitioned so that multiple threads can process the query at the same time. A collection can be divided into parts, each of which is processed by a different thread. When you are done with the partition, you need to merge to get the sum of all the parts.
two。 Divider
The AsParallel () method extends not only the IEnumerable interface, but also the Partitioner class. It allows you to affect the partition you want to create.
The Partitioner class is defined in the System,Collection.Concurrent namespace and has different variations. The Create () method takes an array or object that implements the IList class, as well as parameters of type Boolean, and returns a different Partitioner type. The Create () method has multiple overloaded versions.
Var Q2 = (from x in Partitioner.Create (data) .AsParallel () where Math.Log (x)
< 4 select x).Average(); 也可以对AsParallel()方法接着调用WithExecutionMode()和WithDegreeOfParallelism()方法,来影响并行机制。WithExecutionMode()方法可以传递ParallelExecutionMode的一个Default值或者ForceParallelism值。默认情况下,并行LINQ避免使用系统开销很高的并行机制。WithDegreeOfParallelism()方法,可以传递一个整数值,以指定应并行运行的最大任务数。如果查询不应使用全部CPU,这个方法很有用。 3.取消 要取消长时间运行的查询,可以给查询添加WithCancellation()方法,并传递一个CancellationToken令牌作为参数。CancellationToken令牌从CancellationTokenSource类中创建。 举个例子,下面的查询在单独的线程中运行,如果取消了查询,在该线程中捕获一个OperationCanceledException类型的异常。在主线程中,可以调用CancellationTokenSource类的Cancle()方法取消任务。 var data = SampleData(); var watch = new Stopwatch(); watch.Start(); Console.WriteLine("filled array"); var sum1 = (from x in data where Math.Log(x) < 4 select x).Average(); Console.WriteLine("sync result {0}", sum1); var cts = new CancellationTokenSource(); Task.Factory.StartNew(() =>{try {var res = (from x in data.AsParallel () .WithCancellation (cts.Token) where Math.Log (x))
< 4 select x).Average(); Console.WriteLine("query finished, result: {0}", res); } catch (OperationCanceledException ex) { Console.WriteLine(ex.Message); } }); watch.Stop(); Console.WriteLine("async {0}, result: {1}", watch.ElapsedMilliseconds, "res"); Console.WriteLine("query started"); Console.Write("cancel? "); string input = Console.ReadLine(); if (input.ToLower().Equals("y")) { cts.Cancel(); Console.WriteLine("sent a cancel"); } Console.WriteLine("press return to exit"); Console.ReadLine();二.表达式树 在LINQ To Object 中,扩展方法需要将一个委托类型作为参数,这样就可以将lambda表达式赋予参数。lambda表达式也可以赋予Expression类型的参数,C#编译器根据类型给lambda表达式定义不同的行为。如果类型是Expression,编译器就从lambda表达式中创建一个表达式树,并存储在程序集中。这样就可以在运行期间分析表达式树,并进行优化,以便查询数据源。 var racers = from r in Formula1.GetChampions() where r.Wins >15 & & (r.Country = = "Brazil" | | r.Country = = "Austria") select r
This query expression uses the extension methods Where () and Select (). The Enumerable class defines the Where () method and takes the delegate type Func as a parameter predicate:
Public static IEnumerable Where (this IEnumerable source,Func predicate)
In this way, the lambda expression can be assigned to the delegate predicate.
In addition to using delegates, the compiler places the expression tree in the assembly. The expression tree can be read at run time. The expression tree is built from a class derived from the abstract base class Expression. Expression is different from Expression. Expression classes that inherit from the Expression class include BinaryExpression,ConstantExpression,InvocationExpression and so on. The compiler creates an expression tree from the lambda expression.
For example, the lambda expression r.Country = = "Brazil" uses ParameterExpression,MemberExpression,ConstantExpression,MethodCallExpression to create an expression tree, store it in the assembly, and then use the tree at run time to create an optimized query for the underlying data source:
The / / DisplayTree method graphically displays the expression tree on the console. It passes an Expression object and writes some information about the expression to the console private static void DisplayTree (int indent, string message, Expression expression) {string output = String.Format ("{0} {1}! NodeType: {2}; Expr: {3} "," .PadLeft (indent,'>'), message, expression.NodeType, expression); indent++; switch (expression.NodeType) {case ExpressionType.Lambda: Console.WriteLine (output) LambdaExpression lambdaExpr = (LambdaExpression) expression; foreach (var parameter in lambdaExpr.Parameters) {DisplayTree (indent, "Parameter", parameter);} DisplayTree (indent, "Body", lambdaExpr.Body) Break; case ExpressionType.Constant: ConstantExpression constExpr = (ConstantExpression) expression; Console.WriteLine ("{0} Const Value: {1}", output, constExpr.Value); break Case ExpressionType.Parameter: ParameterExpression paramExpr = (ParameterExpression) expression; Console.WriteLine ("{0} Param Type: {1}", output, paramExpr.Type.Name); break Case ExpressionType.Equal: case ExpressionType.AndAlso: case ExpressionType.GreaterThan: BinaryExpression binExpr = (BinaryExpression) expression If (binExpr.Method! = null) {Console.WriteLine ("{0} Method: {1}", output, binExpr.Method.Name) } else {Console.WriteLine (output);} DisplayTree (indent, "Left", binExpr.Left) DisplayTree (indent, "Right", binExpr.Right); break; case ExpressionType.MemberAccess: MemberExpression memberExpr = (MemberExpression) expression Console.WriteLine ("{0} Member Name: {1}, Type: {2}", output, memberExpr.Member.Name, memberExpr.Type.Name); DisplayTree (indent, "Member Expr", memberExpr.Expression); break Default: Console.WriteLine (); Console.WriteLine ("{0} {1}", expression.NodeType, expression.Type.Name); break } static void Main () {Expression expression = r = > r.Country = = "Brazil" & & r.Wins > 6; DisplayTree (0, "Lambda", expression);}
Output:
An example of using the Expression type is the client provider of ADO.NET EF and WCF data services. These techniques define extension methods with Expression parameters. In this way, the LINQ provider that accesses the database can read the expression, create a query optimized at run time, and get the data from the database.
The use of the expression tree is described separately later.
III. LINQ provider
.net contains several LINQ providers. The LINQ provider implements standard query operators for specific data sources. LINQ providers may implement more extension methods than those defined by LINQ, but at least implement standard operators. LINQ To XML implements some methods specifically for XML, which will be described in more detail later.
The implementation of the LINQ provider is chosen based on the namespace and the type of the first parameter. The namespace of the class that implements the extension method must be open, otherwise the extension method is not in scope. The parameters of the Where () method defined in LINQ to Objects are different from those of the Where () method defined in LINQ To Entities:
The Where () method defined in LINQ to Objects:
Public static IEnumerable Where (this IEnumerable source,Func predicate)
The Where () method defined in LINQ To Entities:
Public static IQueryable Where (this IQueryable source,Expression predicate)
Both classes are implemented in System.Linq 's Syste,.Core assembly. The lambda expression is the same whether you pass parameters using Func or Expression parameters. It's just that the compiler behaves differently, which is selected based on the source parameter. The compiler chooses the best matching method based on its parameters. The ObjectContext class CreateQuery () method defined in ADO.NET EF returns an ObjectQuery object that implements the IQueryable interface, so EF uses the Where () method of the Querable class.
This is the end of the introduction to "how to use LINQ in c #". Thank you for reading. If you want to know more about the industry, you can follow the industry information channel. The editor will update different knowledge points for you every day.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.