Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Order of items after using LINQ Select extension method [duplicate]

Tags:

c#

.net

linq

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
like image 676
John Gathogo Avatar asked Jan 17 '13 13:01

John Gathogo


People also ask

Does LINQ select preserve order?

Therefore, by default, PLINQ does not preserve the order of the source sequence. In this regard, PLINQ resembles LINQ to SQL, but is unlike LINQ to Objects, which does preserve ordering.

Does LINQ Groupby preserve order?

Found answer on MSDN: Yes.

Does ToList preserve order?

The simple answer is no, ToList will just loop over the source enumerable and keep the same order.


1 Answers

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

like image 163
zimdanen Avatar answered Nov 06 '22 00:11

zimdanen