10

Possible Duplicate:
Preserving order with LINQ

Supposing I have the following Person class that is further used to declare an array of Person:

public class Person
{
    public int Id { get;set; }
    public string Name { get; set; }
    public int Age { get; set; }
}

var persons = new[] {
    new Person { Id = 1, Name = "John", Age = 40 },
    new Person { Id = 2, Name = "John", Age = 30 },
    new Person { Id = 3, Name = "John", Age = 35 },
};

I extract the Age from the array of Person, using the following LINQ Select extension method,

var ages = persons.Select(p => p.Age).ToArray;

Does LINQ guarantee that the order of the items in the derived array matches the order of the items in the source array such that the ages array would be in the following order?

40
30
35
Community
  • 1
  • 1
John Gathogo
  • 4,495
  • 3
  • 32
  • 48

5 Answers5

12

The LINQ to Objects operators don't actually change their original data source - they build sequences which are effectively backed by the data source. The only operations which change the ordering are OrderBy/OrderByDescending/ThenBy/ ThenByDescending - and even then, those are stable for equally ordered elements. Of course, many operations will filter out some elements, but the elements which are returned will be in the same order.

From Jon Skeet's answer here.

A breakdown of each operation that returns IEnumerable is further down in that same question: https://stackoverflow.com/a/204777/128217

Community
  • 1
  • 1
zimdanen
  • 5,508
  • 7
  • 44
  • 89
6

Select() preserve the order. It totally does. Just be careful when you use Distinct(), ToDictionary() and ToLookup().

Tommaso Belluzzo
  • 23,232
  • 8
  • 74
  • 98
2

This varies somewhat by which objects and extension methods you use. Here's a post that makes the rundown of the types and what you can expect: Preserving order with LINQ

Community
  • 1
  • 1
Grant H.
  • 3,689
  • 2
  • 35
  • 53
1

Sure!

Items are processed in the order they are in the list.

Teejay
  • 7,210
  • 10
  • 45
  • 76
0

Select for the most part takes an enumerable and applies an operation over each element in order.

You can think of it like this:

public static class Linq
{
    // We take in some data structure that supports enumeration and some function to apply to each element.
    public static IEnumerable<TResult> Select<T, TResult>(this IEnumerable<T> source, Func<T, TResult> operation)
    {
        foreach (var item in source)
        {
            // Here we simply return the next element
            // when the caller wants an item.
            yield return operation(item);
        }
    }
}
Dustin Kingen
  • 20,677
  • 7
  • 52
  • 92
  • 2
    But the question is is guaranteed in specs, or are they allowed to change that behavior in a future implementation? In this case, yes, and that's different than saying it's just a side effect of the current implementation. – Servy Jan 17 '13 at 14:46