Sort list containing custom type on new add

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

Answers


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


If you want to sort list on Add. The best would be to insert item on position that would make List still ordered (with this method complexity is O(N) with any sort method its higer because many sort algorithms perform realy badly on almost sorted collection). Assuming that list is ordered when you add new item:

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

    index++;
}

Need Your Help

How to check for a particular value in a column and delete the entire row corresponding to its value?

excel vba delete-row

I have a set of 100 part numbers in a particular sheet and want to eliminate the data corresponding to those 100 part numbers from my Master Part List sheet (which contains a huge list of parts). I...

how to connect mysql database to desktop java application using jdbc?

java mysql jdbc

how to connect mysql database to desktop java application using jdbc ?

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.