I have ordered list like in example
var someList = new List<int>{1,1,2,3,5,2,1,3,7,1};
I want to select by using LINQ best(highest sum) sequence of 3 numbers. In this case answer is 3,7,1 or 1,3,7. Is that possible without change order or sorting? I have an idea how to do this without LINQ, but I just wanna know to do with LINQ
You can use Skip/Zip to end up with triples. For example:
var triples = list.Zip(list.Skip(1).Zip(list.Skip(2), (b, c) => new { b, c }),
(a, bc) => new { a, bc.b, bc.c });
(That may have some errors - I haven't tested it yet.)
You can then order those triples pretty easily:
var orderedTriples = triples.OrderByDescending(t => t.a + t.b + t.c);
If you're using the triples in multiple contexts, you might want to write an extension method to use Tuple<,,>
instead:
public static IEnumerable<Tuple<T, T, T>> InTriples<T>(this IEnumerable<T> source)
{
// Or potentially write custom code to do this. It wouldn't be too hard...
return source.Zip(list.Skip(1).Zip(list.Skip(2), (b, c) => new { b, c }),
(a, bc) => Tuple.Create(a, bc.b, bc.c));
}
As for whether LINQ is suitable for this - having the InTriples
method generally available means that the rest of the code becomes pretty simple. Using Skip/Zip isn't going to be terribly efficient, but once you've got the code going using that, you can easily rewrite the InTriples
method to use an iteerator block instead.
See more on this question at Stackoverflow