Select linq 函数是否保留 List 集合顺序?
Does Select linq function preserve List collection order?
我想我知道这个问题的答案,但我想与可能比我了解更多的人核实一下。所以这是我正在谈论的一个例子:
var t = 10;
var conditions = new List<Func<int, Tuple<bool, string>>>
{
x => new Tuple<bool, string>(x < 0, "Bad"),
x => new Tuple<bool, string>(x > 100, "Bad"),
x => new Tuple<bool, string>(x == 20, "Bad"),
x => new Tuple<bool, string>(true, "Good")
};
var success = conditions.Select(x => x(t)).First(x => x.Item1);
我正在检查某些数据的多个条件。现在,如果我的 linq 语句 returns 我 "Good" 我可以确定所有条件都是 运行 并且其中 none 评估为真吗?换句话说,Select
返回的集合是否与原始集合具有相同的顺序。我想会的。我错了吗?
.net 现已开源。 Check it out for IList
First()
just takes first element. And Select 只是枚举列表,因此保留了顺序。
至于您的特定 First(x => x.Item1)
案例,它将变成。
foreach (TSource element in source) {
if (element.Item1) return element;
}
其中 source 与 IEnumberable 相似(我删除了一些代码,在您的案例中没有使用)
public Func<int, Tuple<bool, string>> Current {
get { return current; }
}
public override bool MoveNext() {
var enumerator = conditions.GetEnumerator();
while (enumerator.MoveNext()) {
Func<int, Tuple<bool, string>> item = enumerator.Current;
current = item(t);
return true;
}
return false;
}
这取决于底层集合类型 - 如果该类型有定义的顺序(如 List
),那么它会保留顺序。如果项目的顺序未定义(如 Dictionary
、HashSet
),则 "First" 项目不可预测。
我想我知道这个问题的答案,但我想与可能比我了解更多的人核实一下。所以这是我正在谈论的一个例子:
var t = 10;
var conditions = new List<Func<int, Tuple<bool, string>>>
{
x => new Tuple<bool, string>(x < 0, "Bad"),
x => new Tuple<bool, string>(x > 100, "Bad"),
x => new Tuple<bool, string>(x == 20, "Bad"),
x => new Tuple<bool, string>(true, "Good")
};
var success = conditions.Select(x => x(t)).First(x => x.Item1);
我正在检查某些数据的多个条件。现在,如果我的 linq 语句 returns 我 "Good" 我可以确定所有条件都是 运行 并且其中 none 评估为真吗?换句话说,Select
返回的集合是否与原始集合具有相同的顺序。我想会的。我错了吗?
.net 现已开源。 Check it out for IList
First()
just takes first element. And Select 只是枚举列表,因此保留了顺序。
至于您的特定 First(x => x.Item1)
案例,它将变成。
foreach (TSource element in source) {
if (element.Item1) return element;
}
其中 source 与 IEnumberable 相似(我删除了一些代码,在您的案例中没有使用)
public Func<int, Tuple<bool, string>> Current {
get { return current; }
}
public override bool MoveNext() {
var enumerator = conditions.GetEnumerator();
while (enumerator.MoveNext()) {
Func<int, Tuple<bool, string>> item = enumerator.Current;
current = item(t);
return true;
}
return false;
}
这取决于底层集合类型 - 如果该类型有定义的顺序(如 List
),那么它会保留顺序。如果项目的顺序未定义(如 Dictionary
、HashSet
),则 "First" 项目不可预测。