我期待通过一个通用的列表基于一定的参数来寻找项目。
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"));