对包含自定义类型的新添加列表进行排序

本文关键字:添加 列表 排序 自定义 包含 类型 新添加 | 更新日期: 2023-09-27 18:16:06

所以我有一个自定义类型Foo:

public class Foo
{
    public string Description {get;set;}
    public int Order {get;set;} //not unique - just some integer
    public DateTime Date {get;set;}
}

和包含此Foo s的列表(看到我在那里做了什么吗?):

public class FooTops : List<Foo>
{
    public string Description {get; set;}
    public DateTime Date {get; set}
    public void AddCustom(Foo foo)
    {
        if (this.Count == 0)
        {
            this.Description = foo.Description;
            this.Date = foo.Date;
        }
        else
        {
            if (foo.Order == 1)
            {
                this.Date = foo.Date;
            }
        }
        this.Add(foo);
    }
}

我现在想把这个列表转换为SortedList,但是这个列表不能接受我的自定义类型Foo

我如何按Foo.Order排序我的列表?基本上我想有许多FooTops包含Foo s按他们的Foo.Order排序。

我读到关于使用委托来排序列表,但他们总是在之后做,而不是"在每个添加的项目上"。之后我也可以整理我的清单吗?


解决方案:

我刚刚把列表变成了SortedList<int,Foo>。TKey为Foo.Order。当然,这个键不是唯一的,所以在' this. add (foo); '行之前,我只是自己生成一个唯一的键:

private in CheckForUniqueOrder(int p)
{
    if (this.ContainsKey(p))
    {
        p = p +1;
        p = CheckForUniqueOrder(p); //love recursion...
    }
    return p;
}

对包含自定义类型的新添加列表进行排序

如果你想在Add上添加sort列表,最好是在位置上插入项目,使List仍然有序(使用此方法的复杂度是O(N),任何排序方法都更高,因为许多排序算法在几乎排序的集合上表现非常糟糕)。假设在添加新项时列表是有序的:

int index = 0;
foreach(var item in this)
{
    if(item.Order > newItem.Order)
    {
        this.Insert(index, newItem);
        break;
    }
    index++;
}

使用SortedList并使用Foo.Order作为列表的键