【问题标题】:c# System.OutOfMemoryException How can I solve it?c# System.OutOfMemoryException 我该如何解决?
【发布时间】:2017-10-17 04:53:25
【问题描述】:

您好,当我尝试计算超过 24 个元素的组合时,我正在使用此函数来计算对象“Ricerca”列表的所有可能组合,我得到 System.OutOfMemory 异常。有什么办法可以解决这个问题吗?

这是我使用的功能:

 private static List<List<Ricerca>> GetAllCombos(List<Ricerca> list)
    {
        int comboCount = (int)Math.Pow(2, list.Count) - 1;
        List<List<Ricerca>> result = new List<List<Ricerca>>();
        for (int i = 1; i < comboCount + 1; i++)
        {
            // make each combo here
            result.Add(new List<Ricerca>());
            for (int j = 0; j < list.Count; j++)
            {
                if ((i >> j) % 2 != 0)
                    result.Last().Add(list[j]);
            }
        }
        return result;
    }

感谢您的帮助

【问题讨论】:

  • 什么包含类“Ricerca”?此外,您的代码将重复组合,您确定这是您想要的吗?如果您真的想这样做,您可以大大简化代码,只需克隆基本列表并从克隆中删除当前索引。
  • 2^24 = 16777216 - 这很大,你知道吗?如果您认为这 1600 万个元素中的每一个都可以包含多达 24 个元素,那么堆中大约有 4 亿个引用。我不相信你的OutOfMemoryException 一点也不奇怪。
  • 您将 (x * 2**x)) 个项目放入列表中。 List.Count 有多大? x = 24 即 4026353184。
  • @FedericoDipuma 我知道它很大:-(
  • @jdweng 列表的维度不是固定的,所以它可以是任意的

标签: c# visual-studio exception memory out-of-memory


【解决方案1】:

您是否真的需要一次将它们全部保存在内存中,还是一次获得每个组合一个就足够了,以便您可以用它做点什么?

    private static IEnumerable<List<Ricerca>> GetAllCombos(IReadOnlyCollection<Ricerca> list)
    {
        var comboCount = (int)Math.Pow(2, list.Count) - 1;
        for (var i = 1; i < comboCount + 1; i++)
        {
            // make each combo here
            yield return list.Where((t, j) => (i >> j) % 2 != 0).ToList();
        }
    }

【讨论】:

  • 感谢您的回答,在我的代码中,我必须循环所有组合,但也许您是对的,我不需要一次将它们全部保存在内存中。对于每种组合,我必须计算哪个是浪费,我必须只保留那些浪费较少的组合,但当然初始列表的任何元素都必须存在。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-22
  • 2023-01-03
  • 2019-05-10
  • 2021-08-20
  • 2020-08-01
  • 1970-01-01
相关资源
最近更新 更多