在 Linq 中使用 AsParallel 时自定义分块(Partitioners)

本文介绍了如何使用.NET Framework中的Partitioner类创建自定义分块以优化并行处理。通过示例代码展示了如何利用Partitioner.Create方法及AsParallel方法实现并行查询,并介绍了如何进一步调整并行执行模式和并行度。

IEnumerable<T> 接口上有 AsParallel 方法,Partitioner 类上也提供了这个方法,使用这个类我们可以自定义分块的建立。

首先你可以在 System.Collections.Concurrent 命名空间中找到这个类,他提供了一个 Create 方法,第一个参数接受一个数组或者实现 IList<T>的对象,第二个参数是个 Boolean 类型的参数。根据不同的传入参数,该方法返回一个特定分块类型的变量。(比如传入一个数组,返回 DynamicPartitionerForArray<Tsource>StaticPartitionerForArray<TSource>,这些类型都继承自一个虚类OrderablePartitioner<TSource>

下面是实例的代码:

var result = (from x in Partitioner.Create(data, true).AsParallel()
where Math.Log(x) < 4 select x).Average();

你还可以通过调用 WithExecutionMode / WithDegreeOfParallelism 方法来定义其他的分块逻辑。
- WithExecutionMode 传入一个名为ParallelExecutionMode 参数(值为DefaultForceParallelism),Default 方式下能防止过度使用并行处理。
- WithDegreeOfParallelism 传入一个 integer 值来指定最大的并行任务数。

LINQ使用自定义的排序方法,可以通过实现`IComparer<T>`接口或使用Lambda表达式来实现。以下是两种常见的方法: ### 方法一:使用`IComparer<T>`接口 1. 创建一个实现了`IComparer<T>`接口的比较器类。 2. 在LINQ查询中使用`OrderBy`或`OrderByDescending`方法,并传入自定义的比较器。 ```csharp using System; using System.Collections.Generic; using System.Linq; public class CustomComparer : IComparer<string> { public int Compare(string x, string y) { // 自定义比较逻辑 return x.Length.CompareTo(y.Length); } } public class Program { public static void Main() { List<string> words = new List<string> { "apple", "banana", "cherry", "date" }; CustomComparer comparer = new CustomComparer(); var sortedWords = words.OrderBy(word => word, comparer); foreach (var word in sortedWords) { Console.WriteLine(word); } } } ``` ### 方法二:使用Lambda表达式 1. 在LINQ查询中使用`OrderBy`或`OrderByDescending`方法,并传入一个Lambda表达式来定义自定义的排序逻辑。 ```csharp using System; using System.Collections.Generic; using System.Linq; public class Program { public static void Main() { List<string> words = new List<string> { "apple", "banana", "cherry", "date" }; var sortedWords = words.OrderBy(word => word.Length); foreach (var word in sortedWords) { Console.WriteLine(word); } } } ``` ### 方法三:使用`OrderBy`和`ThenBy` 如果需要多级排序,可以在`OrderBy`后使用`ThenBy`或`ThenByDescending`。 ```csharp using System; using System.Collections.Generic; using System.Linq; public class Program { public static void Main() { List<Person> people = new List<Person> { new Person { FirstName = "John", LastName = "Doe" }, new Person { FirstName = "Jane", LastName = "Smith" }, new Person { FirstName = "John", LastName = "Smith" } }; var sortedPeople = people.OrderBy(p => p.FirstName).ThenBy(p => p.LastName); foreach (var person in sortedPeople) { Console.WriteLine($"{person.FirstName} {person.LastName}"); } } } public class Person { public string FirstName { get; set; } public string LastName { get; set; } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值