Coder
Coder

Reputation: 307

sorting list in a list

I have two classes

public class X
{
    string title;
}

public class Y
{
    string name;
    IList<X> testList;
}

I have a list like below

IList<Y> myList = new List<Y>();

I want to sort myList based on the name and title

How can I do it?

Upvotes: 0

Views: 126

Answers (3)

Adil
Adil

Reputation: 148160

Try something like this,

 var sorted = lstY.OrderBy(c => c.name).ToList().Select(d => { d.testList.OrderBy(f => f.title); return d; });

Upvotes: 1

mdisibio
mdisibio

Reputation: 3540

This is one option but not the only option. Add a public or internal getter to class Y:

public IEnumerable<X> TestList{get{return testList.OrderBy(x=>x.title);}}

When retrieving your list of Y, clearly you can sort it by name:

myList.OrderBy(y=>y.name);

And for whatever processing you are doing, such as diplaying the list of Y, you would display Y.name and foreach X in TestList the X.title will be sorted.

or even without that second getter:

myList.OrderBy(y=>y.name).Select(y=>new{y.name, testList=y.testList.OrderBy(t=>t.title)}).Dump();

Upvotes: 0

L.B
L.B

Reputation: 116178

myList.OrderBy(x => x.name).ThenBy(y => y.testList.Min(z=>z.title));

Upvotes: 0

Related Questions