在新添加上包含自定义类型的排序列表

时间:2011-11-30 09:14:51

标签: c# list sorting types

所以我有一个自定义类型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的列表(请参阅我在那里做了什么?):

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包含FooFoo.Order排序。

我读了using delegates来排序列表,但他们总是之后而不是“每个项目添加”。之后我还可以对我的清单进行排序吗?

<小时/> 的解决方案:

我刚刚将列表设为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;
}

2 个答案:

答案 0 :(得分:2)

如果您想在sort列表中添加。最好的方法是在位置上插入项目,使List仍然有序(这种方法复杂度为O(N),任何排序方法都很高,因为许多排序算法在几乎排序的集合上执行得非常糟糕)。假设在添加新项目时订购了列表:

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

    index++;
}

答案 1 :(得分:1)

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