gpt4 book ai didi

c# - 如何在foreach中改进foreach

转载 作者:行者123 更新时间:2023-11-30 19:37:29 25 4
gpt4 key购买 nike

我在 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com