按列表包含的对象的属性对自定义列表进行排序

时间:2015-04-25 11:10:29

标签: c# algorithm sorting collections

我创建了一个非IEnumerable的自定义列表类。因此,我无法使用Enumerable.OrderBy

class MyList<T> 
{
    class ListElement
    {
        public T content;
        public ListElement next;
    }
    ListElement head;
}

在此之后,我在其中放置了具有字符串属性的对象。我想通过它包含的对象的字符串属性对列表进行排序。

2 个答案:

答案 0 :(得分:0)

在这种情况下,最好只使用IEnumerable,甚至更好,只需从列表类派生......我将向您展示如何实现这两者。

public class MyList<T> : IEnumerable<T>
{
    private List<T> itemCollection;

    public MyList()
    {
        this.itemCollection = null;
    }

    public void Add(T item)
    {
        this.itemCollection.Add(item);
    }


    public IEnumerator<T> GetEnumerator()
    {
        foreach (T item in this.itemCollection)
        {
            yield return item;
        }
    }

    /// <summary>
    /// Returns an enumerator that iterates through a collection.
    /// </summary>
    /// <returns>
    /// An <see cref="T:System.Collections.IEnumerator"/> object that can be used to iterate through the collection.
    /// </returns>
    IEnumerator IEnumerable.GetEnumerator()
    {
        return this.GetEnumerator();
    }
}

或者最简单的......

public class MyList<T> : List<T>
{

}

答案 1 :(得分:0)

一个选项不是使用链接列表,而是使用0.761594155955765

另一个是在您的链接列表上实现System.Collections.Generic.List<T>和来自System.Collections.Generic.IEnumerable<T>的构造函数,如下所示:

System.Collections.Generic.IEnumerable<T>

然后,

using System;
using System.Collections.Generic;
using System.Linq;
class MyList<T> : IEnumerable<T> {
    class ListElement {
        public T content;
        public ListElement next;
    }
    ListElement head = null;

    public MyList() {
        head = null;
    }
    public MyList(IEnumerable<T> values)
        : this() {
        ListElement last = null;
        foreach(var v in values) {
            ListElement that = new ListElement { content = v };
            if(last != null) {
                last.next = that;
            } else {
                head = that;
            }
            last = that;
        }
    }

    public IEnumerator<T> GetEnumerator() {
        var current = head;
        while(current != null) {
            yield return current.content;
            current = current.next;
        }
    }
    System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() {
        return this.GetEnumerator();
    }

    public MyList<T> sortedBy<TK>(Func<T, TK> key) {
        return new MyList<T>(this.OrderBy(key));
    }
}

如果你想要排序改变你的列表,而不是新的;或实际排序链表,不转换为数组并排序(IEnumerable.OrderBy似乎这样做), What's the fastest algorithm for sorting a linked list?可能有些用处