Optimization: how do I optimize Linq Concat of Collections? WITH#

Is there a way to optimize this:

public static IEnumerable<IEnumerable<int>> GenerateCombinedPatterns
    (IEnumerable<IEnumerable<int>> patterns1,
     IEnumerable<IEnumerable<int>> patterns2)
{
    return patterns1
           .Join(patterns2, p1key => 1, p2key => 1, (p1, p2) => p1.Concat(p2))
           .Where(r => r.Sum() <= stockLen)
           .AsParallel()
        as IEnumerable<IEnumerable<int>>;
}
+3
source share
2 answers

If you are looking for each combination, use the SelectManyone usually executed with several from statements instead :

return from p1 in patterns1
       from p2 in patterns2
       let combination = p1.Concat(p2)
       where combination.Sum() <= stockLen
       select combination;

This is without any parallelism, though ... depending on the expected collections, I would probably just parallelize at the same level, for example.

return from p1 in patterns1.AsParallel()
       from p2 in patterns2
       let combination = p1.Concat(p2)
       where combination.Sum() <= stockLen
       select combination;

Please note that there is no guarantee regarding the order in which the results come out with the above - you need to configure it if you want to complete the initial order.

+2
source

. : , , , .

public static IEnumerable<IEnumerable<int>> GenerateCombinedPatterns
    (IEnumerable<IEnumerable<int>> patterns1,
     IEnumerable<IEnumerable<int>> patterns2)
{
    var parallel1 = patterns1.AsParallel();
    return parallel1.SelectMany(p1 => patterns2.Select(p2 => p1.Concat(p2)))
        .Where(r => r.Sum() <= stockLen);
}
+1

Source: https://habr.com/ru/post/1759276/


All Articles