I have a list of objects that is added to another list of objects. How do I sort the list by a property in the sub list of objects? See SUDO code below. Any Help would be really appreciated. C#
List<object> MainListOfObject = new List<object>();
List<object> subListObject_0 = new List<object>();
List<object> subListObject_1 = new List<object>();
List<object> subListObject_2 = new List<object>();
cat_a = {Age: 3, Colour: "white"}
cat_b = {Age: 2, Colour: "black"}
cat_c = {Age: 2.5, Colour: "black & white"}
dog_a = {Height: 0.5, EyeColour: "green"}
dog_b = {Height: 0.6, EyeColour: "blue"}
dog_c = {Height: 0.2, EyeColour: "brown"}
Console.WriteLine(cat_a.Age); //output 1
Console.WriteLine(cat_b.Colour); //output "black"
subListObject_0.Add(cat_a);
subListObject_0.Add(dog_a);
subListObject_1.Add(cat_b);
subListObject_1.Add(dog_b);
subListObject_2.Add(cat_c);
subListObject_2.Add(dog_c);
MainListOfObject.Add(subListObject_0);
MainListOfObject.Add(subListObject_1);
MainListOfObject.Add(subListObject_2);
//How do I sort MainListOfObject by nested object property Age?
????? MainListOfObject.OrderBy(o[0] => o[0].Age).ToList(); ?????
Console.WriteLine(MainListOfObject[0][0].Age); //output 2
Console.WriteLine(MainListOfObject[1][0].Age); //output 2.5
Console.WriteLine(MainListOfObject[2][0].Age); //output 3
CodePudding user response:
You should probably just define actual types for your animals. Your example uses anonymous types and objects, and that is just not the way to write c# code.
To define the animals we can use records for a compact way to define a simple type. But a class or struct would work just as well, it would just be a bit more code to write.
To represent a combination of types it is sometimes appropriate to use Tuples, since this support an nice compact syntax:
public record Cat(int Age, string Color);
public record Dog(float Height, string EyeColor);
...
var mainListOfObject = new List<(Cat cat, Dog dog)>();
mainListOfObject.Add((new Cat(3, "white"), new Dog(0.5f, "green")));
var sortedList = mainListOfObject.OrderBy(p => p.cat.Age).ToList();