如何在linq中优化FirstOrDefault语句

alb*_* sh 1 c# linq algorithm performance

我有两个linq语句,第一个需要25毫秒,第二个在100,000循环中需要1100毫秒.

我用ElementAt替换了FirstAll,甚至使用foreach来获取第一个元素,但仍然需要相同的时间.有没有更快的方法来获得第一个元素?

我已经考虑过其他几个问题,但仍然找不到任何解决方案来解决这个问题.

var matches = (from subset in MyExtensions.SubSetsOf(List1)
                where subset.Sum() <= target
                select subset).OrderByDescending(i => i.Sum());
var match = matches.FirstOrDefault(0);
Run Code Online (Sandbox Code Playgroud)

还尝试过:

foreach (var match in matches)
{
    break;
}
Run Code Online (Sandbox Code Playgroud)

甚至:

var match = matches.ElementAt(0);
Run Code Online (Sandbox Code Playgroud)

任何意见将不胜感激.

编辑:这是SubSetOf的代码

public static class MyExtensions
{
    public static IEnumerable<IEnumerable<T>> SubSetsOf<T>(this IEnumerable<T> source)
    {
        // Deal with the case of an empty source (simply return an enumerable containing a single, empty enumerable)
        if (!source.Any())
            return Enumerable.Repeat(Enumerable.Empty<T>(), 1);

        // Grab the first element off of the list
        var element = source.Take(1);

        // Recurse, to get all subsets of the source, ignoring the first item
        var haveNots = SubSetsOf(source.Skip(1));

        // Get all those subsets and add the element we removed to them
        var haves = haveNots.Select(set => element.Concat(set));

        // Finally combine the subsets that didn't include the first item, with those that did.
        return haves.Concat(haveNots);
    }

}
Run Code Online (Sandbox Code Playgroud)

Bac*_*cks 5

你两次打电话给Sum--这很糟糕.预先准备好了:

        var matches = MyExtensions.SubSetsOf(List1)
                        .Select(subset => new { subset, Sum = subset.Sum() })
                        .Where(o => o.Sum < target).OrderByDescending(i => i.Sum);
        var match = matches.FirstOrDefault();
        var subset = match != null ? match.subset : null;
Run Code Online (Sandbox Code Playgroud)