c# System.OutOfMemoryException 我该如何解决?

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

您好,我正在使用此函数来计算对象“Ricerca”列表的所有可能组合,当我尝试计算超过 24 个元素的组合时,我得到了 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;
    }

谢谢你的帮助

最佳答案

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

    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();
        }
    }

关于c# System.OutOfMemoryException 我该如何解决?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44029725/

相关文章:

python - 哪个标准异常类用于违反协议(protocol)?

swift - “ fatal error :在展开可选值时意外发现nil”是什么意思?

没有路由问题的 C# 远程桌面

c# - 为 C# 中的 Func<Type1, Type2> 序列提供简称

visual-studio - 项目配置更改时如何强制重建?

C# 计算重复数字

c# - 如何在 Prism 的 "OnNavigatingTo"中为任何和所有类执行操作

c# - 为测验评分的正确方法

c# - 解决方案资源管理器上缺少 Visual Studio 2022 查看代码按钮

java - 如何处理classCastException