1

Sort the list containing the custom type on the new addition

 11 months ago
source link: https://www.codesd.com/item/sort-the-list-containing-the-custom-type-on-the-new-addition.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Sort the list containing the custom type on the new addition

advertisements

So I have a custom type Foo:

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

and a list containing this Foos (see what I did there?):

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);
    }
}

I now want to convert this list to a SortedList, but that list cannot take my custom type Foo.

How do I sort my list by Foo.Order? Basically I want to have many FooTops containing Foos sorted by their Foo.Order.

I read about using delegates to sort lists but they always do that afterwards and not "on each item added". Could I also sort my list afterwards?


Solution:

I just made the list a SortedList<int,Foo>. The TKey is the Foo.Order. Of course this key is not unique, so before the `this.Add(foo);´ line I just generate a unique key myself:

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


Use the SortedList and use Foo.Order as key for the list.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK