1

I would like to sort a common list in base class from its derived classes.
Each derived class sorts by a different property.

Therefore I use this idea: pass the relevant property to sort the base-class-list by.

protected void SortBy( Func<MyBaseClass, IComparable> getProp)
{
if (BaseClassList != null && BaseClassList .Count > 0)  
 {
  BaseClassList =  BaseClassList 
                  .OrderBy(x => getProp(x))
                  .ToList();
        }

    }

And invoke it from derived classes by SortBy(x => x.GetTop);

Well, now I would like to sort by several properties; for each additional sent property, a ThenBy expression should be added to the method body.

BaseClassList =  BaseClassList 
              .OrderBy(x => getProp(x))  
              .ThenBy(x => x.getOtherProp)
              .ToList();  

Since I do not know how many properties will be sent I would like to use the params idea.
However, I understand it is impossible since 'The parameter array must be a single dimensional array'.

Any ideas?

Community
  • 1
  • 1
user3165438
  • 2,631
  • 7
  • 34
  • 54

1 Answers1

0

Something like this should work:

    public static List<T> SortBy<T>(IEnumerable<T> data, Func<T, IComparable> sort, params Func<T, IComparable>[] details )
    {
        var result  =  data.OrderBy(x => sort(x));

        foreach(var detail in details)
        {
            result = result.ThenBy(x => detail(x));
        }

        return result.ToList();
    }

Please note that I modified it to work with any list and any datatype. You will have to call it with your BaseClassList as first parameter and write the results back again from the return value:

BaseClassList = SortBy(BaseClassList, x => x.GetTop, x => x.GetSecondValue, x => x.GetThirdValue);
nvoigt
  • 75,013
  • 26
  • 93
  • 142
  • Thanks a lot! Great! Is there a way to send a notification if to sort by asc or by descending? how? Thanks in advance! – user3165438 Mar 30 '14 at 08:38