Varun Sharma
Varun Sharma

Reputation: 2759

Order reversed in Aggregate LINQ query

I think the result should contain [1,1,2,2,3,3] but it contains [3,3,2,2,1,1]. Why is the list being reversed?

var sequence = new int[] { 1, 2, 3 };
var result = sequence.Aggregate(
            Enumerable.Empty<int>(),
            (acc, s) => Enumerable.Repeat(s, 2).Concat(acc));

Thanks

Upvotes: 0

Views: 98

Answers (2)

cuongle
cuongle

Reputation: 75316

Simpler way to achieve by using SelectMany:

 var sequence = new int[] { 1, 2, 3 };
 var result = sequence.SelectMany(i => new[] {i, i}).ToArray();

Upvotes: 1

Jeff Mercado
Jeff Mercado

Reputation: 134491

For every item in the sequence, you are concatenating the repetition to the beginning of the accumulated sequence. Swap the order so you are concatenating to the end.

(acc, s) => acc.Concat(Enumerable.Repeat(s, 2))

On a side note, it would be easier (and more efficient) to do this to get that sequence instead.

var result =
    from s in sequence
    from x in Enumerable.Repeat(s, 2)
    select x;

Upvotes: 3

Related Questions