Update: False alarm! The source of the error was elsewhere. (See at the end of the question.)
Is it possible that either Linq or foreach can mess up the order of an array?
One of my testers reported to have experienced that the order of a list of items he fed in as input didn't match the order of the final list that was saved in the database. More precisely, the first element became the last.
So I reviewed my code step by step, and I have no clue what should change the order. There is a Linq query and a foreach loop however. Is it possible that one of these can mess up the order of an array?
Code, simplified:
List<FooBar> fooBarList = new List<FooBar>();
string[][] theData = new string[][] {
new string[] { "a", "x" },
new string[] { "b", "y" },
new string[] { "c", "z" } };
FooBar[] fooBarArray = theData.Select(
row => new FooBar { Foo = row[0], Bar = row[1] }
).ToArray();
foreach (FooBar item in fooBarArray)
{
int iRank = fooBarList.Count + 1;
item.Ranking = iRank;
fooBarList.Add(item);
}
The array of arrays of strings theData
is in fact given as an input. It is transformed into an array of business objects. These are then added to a list and assigned a ranking field. This field is written to the database together with "Foo" and "Bar".
After saving the list in the database, the rank of "a" was 3 in that particular case. For me, however, I cannot reproduce the misbehavior...
Update: I was wrong, the data written to the database was correct. The data I looked to was from a business object that was copied from the original one. When copying, the order was mixed up while reading it from the database, and this wrong order was then persisted in the copy of the object... => Accepted Jon's answer saying "LINQ to Objects generally has a predictable ordering - other providers often don't."