LINQ到陷入困境秩序的阵列?阵列、困境、秩序、LINQ

2023-09-07 05:02:45 作者:旧巷的少女

更新:虚惊!错误的来源是在其他地方。 (见在问题的终结。)

是否有可能,要么LINQ的或的foreach可以搞砸一个数组的顺序?

Is it possible that either Linq or foreach can mess up the order of an array?

我的一个测试报告都经历过的项目列表的顺序,他送入作为输入被保存在数据库中的最终名单的顺序不匹配。更多precisely,第一个元素成为最后一个。

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.

所以,我回顾我的code一步一步,我不知道什么应该改变的顺序。有一个LINQ查询,但foreach循环。难道这些可以搞砸一个阵列的顺序呢?

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,简化为:

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".

在数据库中保存清单后,军衔一是在特定情况下3。但对我来说,我不能重现的不当行为...

更新:我错了,写入到数据库中的数据是正确的我看着这些数据是来自那是的复制的业务对象从原来的。当复制,订单被搞混了,而从数据库中读取它,而这个错误的顺序,然后坚持对象的副本... =>接受Jon的回答说:LINQ到对象一般具有predictable排序 - 其他供应商往往不知道。

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."

推荐答案

那么,你的样品code仅显示LINQ到对象。你是如何将数据插入数据库?如果使用LINQ还有就是,我强烈怀疑它的的LINQ to SQL(或其他)的侧面,它导致了问题,而不是LINQ到对象。

Well, your sample code is only showing LINQ to Objects. How are you inserting the data into the database? If that's using LINQ as well, I strongly suspect that it's the LINQ to SQL (or whatever) side which is causing the issue, not LINQ to Objects.

LINQ到对象一般具有predictable排序 - 其他供应商往往不

LINQ to Objects generally has a predictable ordering - other providers often don't.

编辑:如果发生这种情况可重复,那么你应该能够赶上它发生在调试...这应该给你一些提示。我怀疑,如果你试图创建一个简短而完整的程序,这表明了问题,你最终会发现什么是错的。

If this happens reproducibly, then you ought to be able to catch it happening in the debugger... that should give you some hints. I suspect that if you try to create a short but complete program which demonstrates the problem, you'll end up finding out what's wrong.