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.Orderas key for the list.