Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use multiple OrderBy's to an unspecified number in LINQ?

Tags:

c#

linq

So I know you can use OrderBy like so with LINQ:

MyList.OrderBy(x => x.foo[0].Value).ThenByDescending(x => x.foo[1].Value);

However I am in a situation where I do not know how many properties x.foo will have and I would like to order by all of them. Is this possible?

EDIT: In this instance x.foo is a list of KeyValuePair's where I am sorting by the Value in order of the Keys.

like image 202
aadu Avatar asked Mar 05 '23 13:03

aadu


1 Answers

Provided there's at least one item and all the items have the same number of 'foos'

int foosPerItem = MyList.First().Foo.Count;

IOrderedEnumerable<T> ordered = MyList.OrderBy(x => x.foo[0].Value);

for (int i = 1; i < foosPerItem; i++)
{
    ordered = ordered.ThenByDescending(x => x.foo[i].Value);
}

// added after your comment:
// ordered = ordered.ThenByDescending(x => x.bar);

Following your other comment about ordering by bar first:

IOrderedEnumerable<T> ordered = MyList.OrderBy(x => x.bar);

for (int i = 0; i < foosPerItem; i++)
{
    ordered = ordered.ThenByDescending(x => x.foo[i].Value);
}
like image 117
vc 74 Avatar answered Mar 15 '23 03:03

vc 74