泛型列表的FindAll()主场迎战的foreach [英] Generic list FindAll() vs. foreach

查看:216
本文介绍了泛型列表的FindAll()主场迎战的foreach的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我期待通过一个通用的列表基于一定的参数来寻找项目。

I'm looking through a generic list to find items based on a certain parameter.

一般情况下,这将是最好的,最快的实现?
1.遍历列表中的每个项目,并节省每场比赛为一个新的列表,并返回该

In General, what would be the best and fastest implementation?
1. Looping through each item in the list and saving each match to a new list and returning that

foreach(string s in list)
{ 
    if(s == "match")
    {
       newList.Add(s);
    }
} 

return newList;

或者
2.使用的FindAll方法,并传递一个委托。

Or
2. Using the FindAll method and passing it a delegate.

newList = list.FindAll(delegate(string s){return s == "match";});

难道他们的〜O(N)两种运行?什么是最好的做法在这里?

Don't they both run in ~ O(N)? What would be the best practice here?

问候, 乔纳森

推荐答案

您绝对应该使用的FindAll 方法,或等效的LINQ方法。此外,考虑使用您的代理的更简洁的lambda,而是如果你可以(需要C#3.0):

You should definitely use the FindAll method, or the equivalent LINQ method. Also, consider using the more concise lambda instead of your delegate if you can (requires C# 3.0):

var list = new List<string>();
var newList = list.FindAll(s => s.Equals("match"));

这篇关于泛型列表的FindAll()主场迎战的foreach的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆