complex List<> sorting

  • Thread starter Thread starter Tem
  • Start date Start date
T

Tem

I have an Interface InterfaceBase, and two classes Type 1 and Type 2 that
implements InterfaceBase

Class Type1 has a string property Title
Class Type2 has a string property Title and an int property Ordering

List<BaseC> list

I would like to sort the list by the value of Ordering (Type 1's Ordering is
always 0) and a secondary order by the string property Title alphabetically.

I tried writing my own Comparision code, it doesn't seem to work

Thanks for your help

Tem
 
I have an Interface InterfaceBase, and two classes Type 1 and Type 2 that
implements InterfaceBase

Class Type1 has a string property Title
Class Type2 has a string property Title and an int property Ordering

I assume neither property is part of the interface?
List<BaseC> list

What is BaseC as opposed to InterfaceBase?
I would like to sort the list by the value of Ordering (Type 1's Ordering is
always 0) and a secondary order by the string property Title alphabetically.

I tried writing my own Comparision code, it doesn't seem to work

Could you post some actual code - or maybe a simplified, but
compileable version of what you are trying to do - it is hard to help
without knowing the details or seeing what you tried that didn't work.

Regards,
Gilles.
 
I've decided to use another method to store the data.

Thank you guys for your help.
 
I would like to know how to write this in LINQ

You don't need LINQ for this; you can sort the existing list using a
Comparer<T>:

List<InterfaceBase> list = new List<InterfaceBase>();

list.Sort((x, y) =>
{
int result = x.Ordering.CompareTo(y.Ordering);
if (result == 0) result = string.Compare(x.Title, y.Title);
return result;
});

or in C# 2 (VS2005):

list.Sort(delegate (InterfaceBase x, InterfaceBase y)
{
int result = x.Ordering.CompareTo(y.Ordering);
if (result == 0) result = string.Compare(x.Title, y.Title);
return result;
});

If you really want to use LINQ, you can - but note that you get a new
list - you don't sort the existing one:

List<InterfaceBase> newList = (
from item in list
orderby item.Ordering, item.Title
select item).ToList();

Marc
 

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