【问题标题】:Sort list containing custom type on new add新添加的包含自定义类型的排序列表
【发布时间】:2023-04-01 09:56:01
【问题描述】:

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

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

还有一个包含这个Foos 的列表(看看我在那里做了什么?):

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 包含 Foos 按他们的 Foo.Order 排序。

我读过using delegates 来对列表进行排序,但他们总是这样做之后,而不是“在添加的每个项目上”。之后我也可以对我的列表进行排序吗?


解决方案:

我刚刚将列表设为SortedList&lt;int,Foo&gt;。 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;
}

【问题讨论】:

  • SortedList有什么问题?
  • 不能使用简单的 OrderBy 方法吗?见stackoverflow.com/questions/925571/…
  • @Bond 我猜 Order 不是唯一的
  • 顺序不是唯一的 - 只是用户分配的一些整数。

标签: c# list sorting types


【解决方案1】:

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

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

    index++;
}

【讨论】:

    【解决方案2】:

    使用SortedListFoo.Order 作为列表的键。

    【讨论】:

    • 我采用了您的方法,使密钥自己独一无二(我编辑了问题中的解决方案)。
    猜你喜欢
    • 2012-05-10
    • 1970-01-01
    • 2010-12-31
    • 2019-02-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多