简体   繁体   中英

Order List of Objects by List inside object c#

I have a list of Objects ( obj1 ) and inside each object I have another list of objects like shown below:

List <Obj1> obj1

Obj1

  • string Name
  • List <Obj2> obj2

Obj2

  • string Name
  • int Id

I want to order list of obj1 by order marked by list of obj2 Id s.

First element in list of obj2 defines the order of obj1 list, if they are the same the second one defines order, and so on until end of list of obj2 .

Example data:

  • "Test" : {("A", 2), ("B", 3)}
  • "Test2" : {(("C", 1), ("D", 2)}
  • "Test3" : {(("A", 2), ("B", 2), ("C", 3)}

Result data:

  • "Test2" : {(("C", 1), ("D", 2)}
  • "Test3" : {(("A", 2), ("B", 2), ("C",3)}
  • "Test" : {("A", 2), ("B", 3)}

The following solution will implement the IComparable interface with the int CompareTo(object obj) method for Obj2 and Obj1 .
Obj2 has to be compared by it's Id and Obj1 will be compared by the List<Obj2> .
With that you can call Sort() on a list like: List<Obj1> .

Here on ideone is my full working live example with complete code .

The following are the code snippets needed and described above:

class Obj2 : IComparable
{
    public string Name { get; set; }
    public int Id { get; set; }

    // ...

    public int CompareTo(object obj)
    {
        Obj2 other = obj as Obj2;
        return Id.CompareTo(other.Id);
    }
}

class Obj1 : IComparable
{
    public string Name { get; set; }
    public List<Obj2> Objects { get; set; }

    // ...

    public int CompareTo(object obj)
    {
        Obj1 other = obj as Obj1;
        /* loop until one list ends */
        for (int idx = 0; idx < Objects.Count && idx < other.Objects.Count; ++idx)
        {
            int comparison = Objects[idx].Id.CompareTo(other.Objects[idx].Id);
            /* if not equal return */
            if (comparison != 0)
            {
                return comparison;
            }
        }
        /* if they were equal until now use count to compare */
        return Objects.Count - other.Objects.Count;
    }
}

Resulting Output:

"Test2" : { ("C", 1) ("D", 2) }
"Test3" : { ("A", 2) ("B", 2) ("C", 3) }
"Test" : { ("A", 2) ("B", 3) }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM