簡體   English   中英

.NET中是否有排序的集合類型?

[英]Is there a sorted collection type in .NET?

我正在尋找一個能夠保持所有物品整齊的容器。 我查看了SortedList,但這需要一個單獨的密鑰,並且不允許重復密鑰。 我也可以使用未分類的容器,並在每次插入后顯式排序。

用法:

  • 偶爾插入
  • 經常遍歷順序
  • 理想情況下,不使用與實際對象分開的鍵,使用比較函數進行排序。
  • 期望對等效對象進行穩定的排序,但不是必需的。
  • 不需要隨機訪問。

我意識到我可以建立一個平衡的樹結構,我只是想知道框架是否已經包含這樣的野獸。

您可能想看一下Wintellect Power Collections 它可以在CodePlex上獲得,並且包含很多非常有用的集合。 項目中的OrderedBag集合正是您正在尋找的。 它主要使用紅黑樹來提供非常有效的排序。

只是為了讓EBarr的評論作為答案,自.NET 4.0以來就有SortedSet<T> 當然它是一個集合,這意味着你不能有重復。

如果您只想堅持使用標准集合,那么List<>類的Sort(IComparer<>)函數通常會被忽略。 您需要做的就是為對象創建合適的Comparer<> 例如:

public class PositionDateComparer : IComparer<VehiclePosition>
{
    public int Compare(VehiclePosition x, VehiclePosition y)
    {
        if (x.DateTime == DateTime.MinValue)
        {
            if (y.DateTime == DateTime.MinValue)
            {
                // If x is null and y is null, they're
                // equal. 
                return 0;
            }

            // If x is null and y is not null, y
            // is greater. 
            return -1;
        }

        // If x is not null...
        //
        if (y.DateTime == DateTime.MinValue)
        // ...and y is null, x is greater.
        {
            return 1;
        }

        // ...and y is not null, compare the dates
        //
        if (x.DateTime == y.DateTime)
        {
            // x and y are equal
            return 0;
        }

        if (x.DateTime > y.DateTime)
        {
            // x is greater
            return 1;
        }

        // y is greater
        return -1;
    }
}

然后只要在訪問列表之前對列表進行排序,就執行vehiclePositionsList.Sort(new PositionDateComparer()) 我意識到這可能不像每次添加新對象時自動排序的容器那么簡單,但對於許多人(比如我!)而言,這可能足以成功完成工作而無需任何其他庫。

我會擴展你自己的列表類,如你所提到的,只需在每次插入后進行排序。 由於您的插入很少,因此性能損失最小,並且在任何情況下快速排序幾乎排序的列表。 擴展通用列表並覆蓋Add方法以立即排序。 如果性能成為問題,您可以插入到位以節省一些時間。 此外,您可以對插入進行排隊,以便為要插入的所有值執行單次遍歷插入。

正如我今天早些時候在這里提到的, C5通用集合庫有適合你的容器。

如果鍵也是對象的屬性,則可以嘗試System.Collections.ObjectModel.KeyedCollection<TKey, TItem> 它是一個抽象類,但如果你的鍵只是項目的一個屬性,那么它的衍生起來非常簡單。

這是我在VB6中用來按字母順序排序的舊技巧:使用System.Windows.Forms ListBox對象,並將其“Sorted”屬性設置為true。 在C#中,您可以將任何對象插入到列表框中,它將按照ToString()值的字母順序對對象進行排序:

對於一個類模塊:


使用System.Windows.Forms;

    static void Main(string[] args)
    {
        ListBox sortedList = new ListBox();
        sortedList.Sorted = true;

        sortedList.Items.Add("foo");
        sortedList.Items.Add("bar");
        sortedList.Items.Add(true);
        sortedList.Items.Add(432); 

        foreach (object o in sortedList.Items)
        {
            Console.WriteLine(o);
        }

        Console.ReadKey();
    }

這將顯示:

432
酒吧
FOO
真正

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM