Complex sorting problem with List<>

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

I need some help with a multilevel sorting problem with the List<>.

I have a List<ItemToSort> ( see below ) that needs to be sorted in the
following manner:
Sort by Level1Id ( ok that was the easy part)
Within the unique Level1Id's, sort by Level2Id
Within the unique level2Id's sort by name, then description.

I looked at doing this with some foreach and list.FindAll() and copying the
list into a new list, but this had some code smells. I know there must be a
better solution than making many copies of a list.

The true code is much more complex, and uses custom Comparers, but this
would illustrate the problem. Actually, if I get to the third level (
remember the first one was ez), I can take it from there.

public class ItemToSort
{
public int Level1Id;
public string Level2Id;
public string Name;
public string Description;
}


Not necessarily looking for the code, but some guidlines.
Thanks!
 
use a comparitor and pass it to Sort, with the comparitor something like:

int myCompare(Item first, Item second)
{
if (first.level1id != second.level1.id)
return first.level1id.CompareTo(second.level1id);
if (first.level2id != second.level2id)
return first.level2id.CompareTo(second.level2id);
if (first.Name != second.Name)
return first.Name.CompareTo(second.Name);
return first.Description.CompareTo(second.Description)
}
 
Maybe having your object implement IComparable to reflect your sort
order is all you have to do.

public class ItemToSort : IComparable
{
public int Level1Id;
public string Level2Id;
public string Name;
public string Description;

#region IComparable Members

public int CompareTo(object obj)
{
if(obj == null)
return 1;

ItemToSort obj1 = obj as ItemToSort;

int c = this.Level1Id > obj1.Level1Id ? 1 : (this.Level1Id
== obj1.Level1Id ? 0 : -1);
if (c == 0)
{
c = string.Compare(this.Level2Id, obj1.Level2Id);
}
if (c == 0)
{
c = string.Compare(this.Name, obj1.Name);
}
if (c == 0)
{
c = string.Compare(this.Description,
obj1.Description);
}
return c;
}

#endregion
}
===============
Clay Burch
Syncfusion, Inc.
 
Even better (IMO), use

public class ItemToSort : IComparable<ItemToSort>
{
public int CompareTo(ItemToSort other)
{
}
}

Since the OP uses a List<T> he won't have to worry about sorting against
non ItemToSort objects
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top