Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does LINQ to Objects keep its order

I have a List<Person> and instead want to convert them for simple processing to a List<string>, doing the following:

List<Person> persons = GetPersonsBySeatOrder();
List<string> seatNames = persons.Select(x => x.Name).ToList();

Console.WriteLine("First in line: {0}", seatNames[0]);

Is the .Select() statement on a LINQ to Objects object guaranteed to not change the order of the list members? Assuming no explicit distinct/grouping/ordering is added

Also, if an arbitrary .Where() clause is used first, is it still guaranteed to keep the relative order, or does it sometimes use non-iterative filtering?


As Fermin commented above, this is essentially a duplicate question. I failed on selecting the correct keywords to search stackoverflow

Preserving order with LINQ

like image 805
arserbin3 Avatar asked Jan 09 '13 16:01

arserbin3


People also ask

Does ToList preserve order?

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

Does LINQ order matter?

Yes. But exactly what that performance difference is depends on how the underlying expression tree is evaluated by the LINQ provider. For instance, your query may well execute faster the second time (with the WHERE clause first) for LINQ-to-XML, but faster the first time for LINQ-to-SQL.

What are the uses of LINQ to objects?

In a nutshell, LINQ to Objects provides the developer with the means to conduct queries against an in-memory collection of objects. The techniques used to query against such collections of objects are similar to but simpler than the approaches used to conduct queries against a relational database using SQL statements.

What is LINQ to objects in C#?

The term "LINQ to Objects" refers to the use of LINQ queries with any IEnumerable or IEnumerable<T> collection directly, without the use of an intermediate LINQ provider or API such as LINQ to SQL or LINQ to XML. You can use LINQ to query any enumerable collections such as List<T>, Array, or Dictionary<TKey,TValue>.


2 Answers

In current .Net implementation it use such code. But there are no guarantee that this implementation will be in future.

private static IEnumerable<TResult> SelectIterator<TSource, TResult>(IEnumerable<TSource> source, Func<TSource, int, TResult> selector)
{
  int index = -1;
  foreach (TSource source1 in source)
  {
    checked { ++index; }
    yield return selector(source1, index);
  }
}
like image 141
Andrew Avatar answered Oct 24 '22 19:10

Andrew


It depends on the underlying collection type more than anything. You could get inconsistent ordering from a HashSet, but a List is safe. Even if the ordering you want is provided implicitly, it's better to define an explicit ordering if you need it though. It looks like you're doing that judging by the method names.

like image 32
Samantha Branham Avatar answered Oct 24 '22 21:10

Samantha Branham