我有一个对象集合,我想检索所有其属性与搜索字符串匹配的对象.到目前为止,我已经尝试了一些过滤方法,即List.ForAll,IEnumerable.Where和ParallelQuery.Where.
List<Foo> cache = GetAllObjs(); // source list containing lots of objects
Run Code Online (Sandbox Code Playgroud)
选项1:
List<Foo> foos = cache.AsParallel().Where(x => x.Name == "bar").ToList();
Run Code Online (Sandbox Code Playgroud)
选项2:
List<Foo> foos = cache.Where(x => x.Name == "bar").ToList();
Run Code Online (Sandbox Code Playgroud)
选项3:
List<Foo> foos = cache.FindAll(x => x.Name == "bar");
Run Code Online (Sandbox Code Playgroud)
因为ParallelQuery.Where使用多个内核,所以它似乎是最快的解决方案.除了这些之外,是否还有其他过滤方法,例如使用不同的集合类型或过滤功能?源集合不必是List.
除了这些之外,是否还有其他过滤方法,例如使用不同的集合类型或过滤功能?
如果可以有多个具有相同名称的对象,则可以使用Lookup<string, Foo>.您可以将查找视为string -> List<Foo>字典:
// create
var foosByName = GetAllObjs().ToLookup(x => x.Name, x => x);
// search
var barFoos = foosByName["bar"].ToList();
Run Code Online (Sandbox Code Playgroud)
当然,如果Foo每个名字只有一个,那么经典Dictionary<string, Foo>就会出现.
在字典或查找中搜索(通常)是O(1)操作,而问题中的搜索方法是O(n).
| 归档时间: |
|
| 查看次数: |
2691 次 |
| 最近记录: |