Reputation:
I'm trying use AsParallell()
with AsOrdered()
method, but always I see unordered results.
using System;
using System.Linq;
using System.Collections.Generic;
namespace Parallel
{
class MainClass
{
public static void Main(string[] args)
{
List<String> cities = new List<String>() {
"Barcelona",
"Valencia",
"Sevilla",
"Zaragoza",
"Málaga",
"Murcia",
"Palma",
"Las Palmas de Gran Canaria",
"Alicante",
"Madrid",
"Córdoba",
"Valladolid",
"Tarrasa",
"Vigo",
"Gijón",
"Cartagena",
"Hospitalet de Llobregat",
"Vitoria",
"La Coruña",
"Granada",
"Elche",
"Oviedo",
"Badalona"
};
var filtered = cities.AsParallel().AsOrdered().Where(c => c.ToUpper().StartsWith("B") || c.ToUpper().EndsWith("A")).ToArray();
Console.WriteLine("Cities starting with \"B\" or ends with \"A\"");
foreach (String city in filtered)
{
Console.WriteLine(city);
}
}
}
}
The output is:
Cities starting with "B" or ends with "A" Barcelona Valencia Sevilla Zaragoza Málaga Murcia Palma Las Palmas de Gran Canaria Córdoba Tarrasa Cartagena Vitoria La Coruña Granada Badalona Press any key to continue...
Whats wrong?
I'm using Visual Studio in Mac, Net Core project.
Thanks
Upvotes: 2
Views: 214
Reputation: 169270
AsOrdered()
just maintains the original order of the items in the List<string>
. If you want to order the items alphabetically you could use the OrderBy
method:
var filtered = cities.AsParallel().Where(c => c.ToUpper().StartsWith("B") || c.ToUpper().EndsWith("A")).OrderBy(x => x).ToArray();
Upvotes: 2
Reputation: 101493
AsOrdered
does not mean it will sort your collection. AsOrdered
means it will preserve existing ordering. Because your collection is initially unordered - your results are unordered too.
If you will do
cities.Sort();
before parallel query - your results will be ordered. However, if you do this but remove AsParallel
- your results are not guaranteed to be ordered.
Upvotes: 0