'Can an Order be guranteed if return type is IEnumerable?

I am currently working on refactoring some code, and came across this method.

    public IEnumerable<KeyValuePair<string, string>> GetDataItems()

which does this

    var data = EditorService
        .GetAllItem()
       .OrderBy(x => x.name);

    var list = new List<KeyValuePair<string, string>>();

    foreach (var item in data)
    {
        string guid = item.guid;
        string name = item.name;
        list.Add(new KeyValuePair<string, string>(guid, name));
    }

    return list;

I am bit confused on whether the order itself make sense? IEnumerable as I understand don't ensure that objects in the list is not ordered? But in this case the underlying model is a list, will order then be guranteed? or will this be ignored once it is returned?



Solution 1:[1]

The variable data you show on your code snippet is of type System.Linq.IOrderedEnumerable returned by that OrderBy linq statement. The items you inserted on your returned list are ordered because of that. New items you add on that list, as you told, are not guranteed their order.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Fran Aguilar