OrderBy Linq的奇怪行为 [英] Strange behaviour of OrderBy Linq

查看:121
本文介绍了OrderBy Linq的奇怪行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用OrderBy() Linq函数排序的列表,该列表返回IOrderedEnumerable.

I have a list which is ordered using the OrderBy() Linq function, that returns an IOrderedEnumerable.

var testList = myList.OrderBy(obj => obj.ParamName);

ParamName是一个可以容纳整数和字符串的对象.上面的orderBy基于整数值对列表进行排序.现在,我在testList上操作一个foreach,并根据其整数值将ParamName属性更改为某些字符串,如下所示,

The ParamName is an object that can hold integer as well as string. The above orderBy orders the list based on the integer value. Now I am operating a foreach on the testList and changing the ParamName property to some string based on its integer value as follows,

using (var sequenceEnum = testList.GetEnumerator())
{
    while (sequenceEnum.MoveNext())
    {
        sequenceEnum.Current.ParamName = GetStringForInteger(int.Parse(Convert.ToString(sequenceEnum.Current.ParamName)));
    }
}

接下来发生的是,在上一个循环之后,列表中各项的顺序已中断,并且列表是根据分配的字符串而不是根据初始顺序进行排序的.

What has happened next is that the order of the items in the list after the previous loop has been disrupted and the list has been ordered based on the string assigned and not on the initial ordering.

但是,当我将.ToList().OrderBy()子句结合使用时,会保留顺序.

However the ordering is preserved, when I am using .ToList() in conjunction with the .OrderBy() clause.

有人可以帮我这里发生什么事吗?

Can anyone please help me what is happening here?

示例输出图示:

推荐答案

我们都把你的问题弄错了.它排序错误的原因是因为您正在比较"B"和"AA",并期望AA像excel中那样位于B之后,所以当然不会按字母顺序出现.

We all got your problem wrong. The reason it is sorting the wrong way is because you are comparing "B" and "AA" and expecting AA to be after B like in excel which of course will not happen in an alphabetical order.

在排序时指定一个显式比较器,或者在进行排序之前将ParamName转换为Int.

Specify an explicit comparator while ordering or transform the ParamName into Int before doing the order by.

Linq通常返回IEnumerable元素的原因是它具有懒惰的评估行为.这意味着它将在需要时而不是在构建时评估结果.

The reason why Linq is usually returning IEnumerable elements is that it has a lazy evaluation behaviour. This means that it will evaluate the result when you need it, not when you build it.

调用ToList会强制linq评估结果以生成预期的列表.

Calling the ToList forces linq to evaluate the result in order to generate the expected list.

TL; DR在执行linq查询并在获取结果之前更改源数据集时要格外小心.

TL;DR be very carefull when doing linq queries and altering the source data set before fetching the result.

这篇关于OrderBy Linq的奇怪行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆