New string list shuffles order of list elements on initialization in LINQ

After running into some frustrations with my ASP.NET 5 API project I decided to rebuild it as an older WebApi 2 project. I’m trying to generate a list of collections of 2 strings (originally a list of a 2 element string array, now a list of list of strings) from a LINQ query.

Here is the pseudocode that worked as I wanted it to in the ASP.NET 5 project:

var testList = db.MyTable.Where(x => [WHERE Clauses]).Select(x => new string[] { x.Number.Trim(), x.Name.Trim() }).ToList();

The new project choked on the query citing it didn’t like using string arrays for whatever reason (I’m assuming difference in EF 6 vs 7?). As a fix I instead had the query return a list of string lists but it mixes up the order of the “Number” and “Name” fields it returns, sometimes the Number is the first element and other times the Name is. Here is some new query code attempts I tried that all ended up with the jumbled element order:

var testList = db.MyTable.Where(x => [WHERE Clauses]).Select(x => new List<string> { x.Number.Trim(), x.Name.Trim() }).ToList();
var testList = db.MyTable.Where(x => [WHERE Clauses]).Select(x => (new string[2] { x.Number.Trim(), x.Name.Trim() }).ToList()).ToList();
var testList = db.MyTable.Where(x => [WHERE Clauses]).Select(x => new List<string>(new string[] { x.Number.Trim(), x.Name.Trim() })).ToList();

I realize there are a ton of different ways to get the end result I’m looking for but I’m hoping someone can help me understand why these list elements would be placed in the list in differing orders (sometimes Name then Number other times Number then Name), even when I generate a list based on a newly created array which preserved the order perfectly previously.

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

I’d be curious to see what SQL is generated for those queries and whether or not it changes when your result changes. Selecting a List to me seems like a pretty rare situation, so it’s possible you have run into an edge-case (or at least into undefined behavior territory).

Since you’re still essentially just selecting two columns, we can worry about how the data is structured after Entity Framework has finished it’s work

db.MyTable.Where(x => [WHERE Clauses])
    .Select(x => new { Number = x.Number.Trim(), Name = x.Name.Trim() })
    .AsEnumerable() //Force EF to materialize the result here
    .Select(x => new List<string> { x.Number, x.Name }) //Manipulate the result in memory

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply