c# - 如何在foreach中改进foreach

标签 c#

我在 foreach 循环中有一个 foreach 循环,如下所示:

// Item is an abstract class. Item1, Item2, etc. are his heirs.
List<Item> allItems = new List<Item> { new Item1(), new Item2(), new Item3(), new Item4() };
List<Type> affectedItems = new List<Type> { typeof(Item1), typeof(Item3) };

foreach(Item i in allItems)
    foreach(Type t in affectedItems)
        if(i.GetType().Equals(t))
        {
            // does something
        }

如何改进我的代码,使内部循环不会浪费太多时间检查列表中不存在的项目?

最佳答案

您使用的任何 linq 扩展方法(例如 WhereAny)都是一个额外的循环。

您需要尽量减少循环(尤其是嵌套循环)的数量,在您的情况下,最好的方法是使用快速查找数据结构:

List<Item> allItems = new List<Item>{ new Item1(), new Item2(), new Item3(), new Item4() };

HashSet<Type> affectedItems = new HashSet<Type>(){ typeof(Item1), typeof(Item3) };

foreach (Item i in allItems)
{
    if (affectedItems.Contains(i.GetType()))
    {
        // Do Something
    }
}

这是迄今为止最快的方法,循环次数最少,最多需要 0.02 毫秒,而其他方法最多需要 0.7

一个快速建议,每当你有循环过程并且你想要优化查找数据结构以使用像HashSet, Dictionary, 查找等。

关于c# - 如何在foreach中改进foreach,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37959811/

相关文章:

c# - Unity 后处理 - 在代码中更改绽放的颜色

c# - 如何让触摸屏在 C# 应用程序中使用鼠标事件而不是触摸事件

c# - 无法让 .Dispose() 在 foreach 循环中工作

c# - 使用 Task.Run 时避免捕获当前执行上下文

c# - 使用 PageFactory 初始化时 IWebElement 没有属性

c# - ASP.NET MVC 绑定(bind)到字典

c# - 如何使用 'Directory.getFiles' 获取磁盘上具有特定扩展名的所有文件并将它们保存在列表中

c# - ASP.NET MVC。如何使用 DisplayNameFor 来创建表格标题和正文?

c# - 代码在 c# dll 和 powershell 中表现不同

c#,如何读取xml内部元素