泛型列表的FindAll()主场迎战的foreach主场、列表、FindAll、foreach

2023-09-03 09:30:02 作者:有你的夜晚群星闪耀

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

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"));