简体   繁体   中英

Does Select linq function preserve List collection order?

I think I know the answer to this question, but I wanted to double check with people who perhaps know more than me. So here's an example of what I'm talking about:

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);

I'm checking for multiple conditions on some data. Now, if my linq statement returns me "Good" can I be certain that all of the conditions were run and that none of them evaluated to true? In other words, would the collection returned by Select have the same order as the original collection. I think it would. Am I wrong?

.net is open sourced now. Check it out for IList First() just takes first element. And Select just enumerates list, so order is preserved.
As for your particular First(x => x.Item1) case it will turn into.

foreach (TSource element in source) {
    if (element.Item1) return element;
}

where source is similar to that IEnumberable (I've removed some code, which is not used in your case)

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;
}

It depends on the underlying collection type - if the type has a defined order (like List ), then yes it will preserve order. If the order of items in not defined (like Dictionary , HashSet ) then the "First" item is not predictable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM