首页 > 解决方案 > 当我将 LINQ 方法应用于 SortedDictionary 时,Unity 冻结。会是什么呢?

问题描述

因此,我正在 Unity 中制作游戏,并且我最近更改了代码中的一个列表,用于 SortedDictionary<Datetime, SomeClass>。但是当我应用 LINQ 方法 Last() 或 ElementAt() 时,Unity 只会冻结,甚至不会发送错误消息。它只是冻结。在我的代码中没有while循环,所以不是无限循环。只有一个简单的 for循环和一些 if 语句。

这是有问题的代码,我用可能的错误标记了这些行:

public SortedDictionary<DateTime, Quote> PricePattern(Stock s, int days, float trend)
{
    SortedDictionary<DateTime, Quote> quotes = new SortedDictionary<DateTime, Quote>();

    for (int i = 0; i < days; i++) {
        Quote q = new Quote();
        float a = Calculations.SampleGaussian(0f, 0.01f);

        q.openPrice = 0;
        q.minPrice = 0;
        q.maxPrice = 0;
        q.volume = 0;

        if (i == 0) {
            q.closePrice = Mathf.Round(100 * s.currentPrice * (1 + trend + a)) / 100;
        } else {
            q.closePrice = Mathf.Round(100 * quotes.Last().Value.closePrice * (1 + trend + a)) / 100; //PROBLEM HERE
        }

        if (days == 1) {
            q.date = TimeController.currDay;
        } else if (i == 0) {
            q.date = s.ipoDay;
        } else if (i > 0){
            q.date = quotes.Last().Key.AddDays(1).CheckIfWeekDay(); //PROBLEM HERE
        }

        quotes.Add(q.date, q);
    }

    if (days > 1) {
        List<DateTime> datesToRemove = new List<DateTime>();
        for (int i = quotes.Count - 1; i > quotes.Count - 15; i--) {
            if (quotes.ElementAt(i).Key >= TimeController.currDay) { //PROBLEM HERE
                datesToRemove.Add(quotes.ElementAt(i).Key); //PROBLEM HERE
            } else {
                break;
            }
        }
        foreach (DateTime item in datesToRemove) {
            quotes.Remove(item);
        }
        datesToRemove.Clear();
    }

    return quotes;
}

有谁知道会是什么?我被困在里面两天了。

标签: c#linqunity3d

解决方案


我会留下我的最后一条评论作为答案(但不会接受它,因为我正在等待@Igor 发布他的答案),所以它可以对其他人有所帮助。

我犯了几个错误,所以我将在这里留下一些我在尝试修复代码时学到的建议:

  1. 如果您需要创建大尺寸的列表或字典,请使用预定义的容量创建它。这将节省大量时间,并且您的收藏不需要每次都调整大小。
  2. 如果您需要使用 SortedDictionary 并在开始时填充大量数据,请先创建 Dictionary,然后将其转换为 SortedDictionary。

如何将容量设置为列表或字典

int capacity = 500;

List<T> exampleList = new List<T>(capacity);

Dictionary<TKey, TValue> exampleDictionary = new Dictionary<TKey, TValue>(capacity);

将字典转换为 SortedDictionary

Dictionary<TKey, TValue> exampleDictionary = new Dictionary<TKey, TValue>();

SortedDictionary<TKey, TValue> exampleSortedDictionary = new SortedDictionary<TKey, TValue>(exampleDictionary);

推荐阅读