共用方式為


HOW TO:控制 PLINQ 查詢中的順序

這些範例顯示如何使用 AsOrdered 擴充方法來控制 PLINQ 查詢中的順序。

注意事項警告

這些範例主要是為了示範用法,執行速度不一定比對應的循序 LINQ to Objects 查詢更快。

範例

下列範例會保留來源序列的順序。 這有時候是必要的,例如某些查詢運算子需要已排序的來源序列,才能產生正確的結果。

Sub OrderedQuery()

    Dim source = Enumerable.Range(9, 10000)

    ' Source is ordered let's preserve it.
    Dim parallelQuery = From num In source.AsParallel().AsOrdered()
                            Where num Mod 3 = 0
                            Select num

    ' Use For Each to preserve order at execution time.
    For Each item In parallelQuery
        Console.Write("{0} ", item)
    Next

    ' Some operators expect an ordered source sequence.
    Dim lowValues = parallelQuery.Take(10)

End Sub
var source = Enumerable.Range(9, 10000);

// Source is ordered; let's preserve it.
var parallelQuery = from num in source.AsParallel().AsOrdered()
                    where num % 3 == 0
                    select num;

// Use foreach to preserve order at execution time.
foreach (var v in parallelQuery)
    Console.Write("{0} ", v);

// Some operators expect an ordered source sequence.
var lowValues = parallelQuery.Take(10);

下列範例顯示一些可能需要已排序來源序列的查詢運算子。 這些運算子對未排序的序列同樣能運作,但可能會產生未預期的結果。

' Paste into PLINQDataSample class
Shared Sub SimpleOrdering()
    Dim customers As List(Of Customer) = GetCustomers().ToList()

    ' Take the first 20, preserving the original order

    Dim firstTwentyCustomers = customers _
                                .AsParallel() _
                                .AsOrdered() _
                                .Take(20)

    Console.WriteLine("Take the first 20 in original order")
    For Each c As Customer In firstTwentyCustomers
        Console.Write(c.CustomerID & " ")
    Next

    ' All elements in reverse order.
    Dim reverseOrder = customers _
                        .AsParallel() _
                        .AsOrdered() _
                        .Reverse()

    Console.WriteLine(vbCrLf & "Take all elements in reverse order")
    For Each c As Customer In reverseOrder
        Console.Write("{0} ", c.CustomerID)
    Next
    ' Get the element at a specified index. 
    Dim cust = customers.AsParallel() _
                        .AsOrdered() _
                        .ElementAt(48)

    Console.WriteLine("Element #48 is: " & cust.CustomerID)

End Sub
// Paste into PLINQDataSample class.
static void SimpleOrdering()
{

    var customers = GetCustomers();

    // Take the first 20, preserving the original order
    var firstTwentyCustomers = customers
                                .AsParallel()
                                .AsOrdered()
                                .Take(20);

    foreach (var c in firstTwentyCustomers)
        Console.Write("{0} ", c.CustomerID);

    // All elements in reverse order.
    var reverseOrder = customers
                        .AsParallel()
                        .AsOrdered()
                        .Reverse();

    foreach (var v in reverseOrder)
        Console.Write("{0} ", v.CustomerID);

    // Get the element at a specified index. 
    var cust = customers.AsParallel()
                        .AsOrdered()
                        .ElementAt(48);

    Console.WriteLine("Element #48 is: {0}", cust.CustomerID);

}

若要執行這個方法,請將方法貼至 PLINQ 資料範例專案中的 PLINQDataSample 類別,然後按 F5。

下列範例顯示如何保留查詢中第一個部分的順序,接著移除順序以增加 join 子句的效能,然後再將順序重新套用至最終結果序列。

' Paste into PLINQDataSample class
Sub OrderedThenUnordered()
    Dim Orders As IEnumerable(Of Order) = GetOrders()
    Dim orderDetails As IEnumerable(Of OrderDetail) = GetOrderDetails()

    ' Sometimes it's easier to create a query
    ' by composing two subqueries
    Dim query1 = From ord In Orders.AsParallel()
             Where ord.OrderDate < DateTime.Parse("07/04/1997")
             Select ord
             Order By ord.CustomerID
             Take 20

    Dim query2 = From ord In query1.AsUnordered()
             Join od In orderDetails.AsParallel() On ord.OrderID Equals od.OrderID
            Order By od.ProductID
            Select New With {ord.OrderID, ord.CustomerID, od.ProductID}


    For Each item In query2
        Console.WriteLine("{0} {1} {2}", item.OrderID, item.CustomerID, item.ProductID)
    Next
End Sub
// Paste into PLINQDataSample class.
static void OrderedThenUnordered()
{

    var orders = GetOrders();
    var orderDetails = GetOrderDetails();

    var q2 = orders.AsParallel()
       .Where(o => o.OrderDate < DateTime.Parse("07/04/1997"))
       .Select(o => o)
       .OrderBy(o => o.CustomerID) // Preserve original ordering for Take operation.
       .Take(20)
       .AsUnordered()  // Remove ordering constraint to make join faster.
       .Join(
              orderDetails.AsParallel(),
              ord => ord.OrderID,
              od => od.OrderID,
              (ord, od) =>
              new
              {
                  ID = ord.OrderID,
                  Customer = ord.CustomerID,
                  Product = od.ProductID
              }
             )
       .OrderBy(i => i.Product); // Apply new ordering to final result sequence.

    foreach (var v in q2)
        Console.WriteLine("{0} {1} {2}", v.ID, v.Customer, v.Product);

}

若要執行這個方法,請將方法貼至 PLINQ 資料範例專案中的 PLINQDataSample 類別,然後按 F5。

請參閱

參考

ParallelEnumerable

概念

平行 LINQ (PLINQ)