How to sort an IEnumerable

后端 未结 4 874
执笔经年
执笔经年 2020-12-24 03:59

How can I sort an IEnumerable alphabetically. Is this possible?

Edit: How would I write an in-place solution?

4条回答
  •  一个人的身影
    2020-12-24 04:49

    The same way you'd sort any other enumerable:

    var result = myEnumerable.OrderBy(s => s);
    

    or

    var result = from s in myEnumerable
                 orderby s
                 select s;
    

    or (ignoring case)

    var result = myEnumerable.OrderBy(s => s,
                                      StringComparer.CurrentCultureIgnoreCase);
    

    Note that, as is usual with LINQ, this creates a new IEnumerable which, when enumerated, returns the elements of the original IEnumerable in sorted order. It does not sort the IEnumerable in-place.


    An IEnumerable is read-only, that is, you can only retrieve the elements from it, but cannot modify it directly. If you want to sort a collection of strings in-place, you need to sort the original collection which implements IEnumerable, or turn an IEnumerable into a sortable collection first:

    List myList = myEnumerable.ToList();
    myList.Sort();
    

    Based on your comment:

    _components = (from c in xml.Descendants("component")
                   let value = (string)c
                   orderby value
                   select value
                  )
                  .Distinct()
                  .ToList();
    

    or

    _components = xml.Descendants("component")
                     .Select(c => (string)c)
                     .Distinct()
                     .OrderBy(v => v)
                     .ToList();
    

    or (if you want to later add more items to the list and keep it sorted)

    _components = xml.Descendants("component")
                     .Select(c => (string)c)
                     .Distinct()
                     .ToList();
    
    _components.Add("foo");
    _components.Sort();
    

提交回复
热议问题