-2

I have a List of a List which contains an object.

List<List<Field>> records;

The Field object contains ID and Value.

I need to sort the top level List using attributes of the Field record.

The sort needs to say, for every record, select a list using an ID and then sort the parent by the value.

So if I had 2 records they would look like this:

  List[0] -> List [ID=1 Value="Hello", ID=2 Value="World"]
  List[1] -> List [ID=1 Value="It's", ID=2 Value="Me"]

using ID 1 would select the object in the child list and then sort the parent object. If, for example, the ID was 2, the sort would swap the 0 and 1 items, as Me comes before World.

Is there a simple way to do this?

Thanks.

MethodMan
  • 18,625
  • 6
  • 34
  • 52
Grey
  • 11
  • 2

1 Answers1

1

Here's an example of what you're looking for:

using System; using System.Collections.Generic; using System.Linq;

public class Program
{
  public static void Main()
  {
    var structure = new List<List<string>>();
    structure.Add(new List<string>() {"Hello", "World"});
    structure.Add(new List<string>() {"It's", "Me"});

    SortBySubIndex(structure, 0);
    SortBySubIndex(structure, 1);
  }

  public static void SortBySubIndex(List<List<string>> obj, int index) 
  {
    obj = obj.OrderBy(list => list[index]).ToList();
    Console.WriteLine("INDEX: " + index);
    Console.WriteLine(obj[0][0]);
    Console.WriteLine(obj[1][0]);   
    Console.WriteLine();
  }
}
Austin
  • 1,291
  • 10
  • 19