c# - Linq Expression Slow - 如果可能需要优化

标签 c# performance linq time-complexity

我有一个整数列表“numberRangeList”,其中包含按顺序从 62 到 92 的 31 个整数,我正在提取第二个整数列表“extractedList”,它将包含 10 个总和等于“total”的整数。问题是计算大约需要 30 秒,有什么方法可以加快速度吗??

        var numberRangeList = new List<int>() { 62, 63, ...92 };
        var total = 772;
        var extractedList= (from n1 in numberRangeList
                      from n2 in numberRangeList
                      from n3 in numberRangeList
                      from n4 in numberRangeList
                      from n5 in numberRangeList
                      from n6 in numberRangeList
                      from n7 in numberRangeList
                      from n8 in numberRangeList
                      from n9 in numberRangeList
                      from n10 in numberRangeList
                      where n1 + n2 + n3 + n4 + n5 + n6 + n7 + n8 + n9 + n10 == total
                      select new List<int> { n1, n2, n3, n4, n5, n6, n7, n8, n9, n10 }).Take(1).First();

最佳答案

性能问题不在LINQ,而在问题本身。 这个问题在 CS 文献中是众所周知的,它被称为子集和 http://en.wikipedia.org/wiki/Subset_sum_problem .这是属于 NP 完全类时间复杂性 (http://en.wikipedia.org/wiki/NP-complete) 的已知问题。如果您不想探索(指数)问题的复杂性,则应该对次优解决方案进行一些研究。

关于c# - Linq Expression Slow - 如果可能需要优化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24340890/

相关文章:

c# - 错误 :check the manual that corresponds to your MySQL server version for the right syntax to use near

c# - 在 ASP.NET Web API 中处理错误的正确方法

阻塞的 python 程序占用 6% 的 CPU?

c# - 如何在 MVC Controller 中返回 json 中的列表 linq?

c# - 跨线程读取值不重要的变量

c# - 如果在数据库中找不到记录,则返回 (RecordNotFound) 异常或 null?

javascript - 循环中javascript中函数声明与函数表达式的性能

python - 如何提高 Cython 的性能?

xml - 根据同胞的值选择 XML 元素

c# - 从 C# 字典中获取特定值的列表