Search code examples
c#linqselectcollections

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?


Solution

  • .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 IEnumerable (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;
    }