Fastest way to filter a collection C#

时间:2016-02-12 21:47:57

标签: c# search

I've a collection of objects, and I'd like to retrieve all objects that have one of its properties match a search string. So far I've tried a few methods of filtering, namely List.ForAll, IEnumerable.Where, and ParallelQuery.Where.

use strict ;
use warnings;
use Math;

my $math_action = new Math();
my $number1 = 5;
my $number2 = 3;
my $results = Math::add($number1, $number2);
print $results;

Option 1:

List<Foo> cache = GetAllObjs(); // source list containing lots of objects

Option 2:

List<Foo> foos = cache.AsParallel().Where(x => x.Name == "bar").ToList();

Option 3:

List<Foo> foos = cache.Where(x => x.Name == "bar").ToList();

Because ParallelQuery.Where utilises multiple cores, it appears to be the fastest solution. Other than these, are there other methods of filtering, such as using different collection types, or filtering functions? The source collection doesn't have to be a List.

1 个答案:

答案 0 :(得分:9)

Other than these, are there other methods of filtering, such as using different collection types, or filtering functions?

If you can have multiple objects with the same name, you can use a let authString = NSString(format: "%@, @%", clientID, clientSecret). You can think of a lookup as a Lookup<string, Foo> dictionary:

string -> List<Foo>

Of course, if there is only one // create var foosByName = GetAllObjs().ToLookup(x => x.Name, x => x); // search var barFoos = foosByName["bar"].ToList(); for every name, a classic Foo will serve.

Searching in a dictionary or lookup is (usually) an O(1) operation, whereas the search methods in your question are O(n).