Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to sort a List of complex objects in c#

How can I sort a List<object> where the object is always List<string>.
I know that there is already questions similar to this one.. I tried Sort() or other functions that was suggested but I couldn’t solve.

This is what I have:

var result= new List<object>();

foreach (var data in myData)
{
  result.Add(new List<string>() { data.Text, myData.Count().ToString() });                     
}
//This is how at the end the List<object> looks like:
[
    [
        "xxx",
        "2"
    ],
    [
        "xxxx",
        "2"
    ],
    [
        "xxx",
        "2"
    ],
    [
        "xxxx",
        "3"
    ],
    [
        "xxx",
        "48"
    ],
    [
        "xxxx"
        "18"
    ],
    [
        "xxxx",
        "58"
    ],
    [
        "xxxx",
        "1"
    ],
    [
        "xxxx",
        "371"
    ],
    [
        "xxxx",
        "3"
    ],
    [
        "xxxxx",
        "2"
    ]
]

I need to order the List<object> by the second element of the list whis is always numer

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can sort the list like this:

data = data.OrderBy(i => int.Parse(i[1])).ToList();

But we can do even better if we skip the intermediate step in the question, and start with myData:

var data = myData.Select(md => (md.Text, md.Count())).OrderBy(md => md.Item2);

This is better for two reasons:

  1. It lets us keep the int value in a more-precise type. Thanks to internationalization/cultural issues, converting back and forth between numbers or dates and strings is far slower and more error prone than we’d like to believe. It’s therefore something to avoid. It’s usually far better to keep the specialized numeric data for as long as possible, and only convert to strings at the last possible moment. In this case, we save the conversion operation twice (once in each direction), and so this code should already be MUCH faster than the original.

  2. We end up with an IEnumerable<(string, int)>, instead of a List<List<string>>. IEnumerable<T> is almost always greatly more efficient than List<T>, because of the reduced memory use and the ability to stream data as it comes, instead of needing to load the entire set up front.

If you really need the janky List<List<string>> you can do this:

var data = myData.OrderBy(md => md.Count()).
     Select(md => new List<string>{md.Name, md.Count().ToString()}).
     ToList();

Note that because of the points above, even when we really want the list the most efficient way to get there was still to preserve the original int for ordering and craft the IEnumerable before creating the final list, and depending on how long it takes to run Count() it might even be more efficient to use my main suggestion of IEnumerable<(string, int)> as the intermediate step:

var data = myData.Select(md => (md.Text, md.Count())).
    OrderBy(md => md.Item2).
    Select(md => new List<string> {md.Item1, md.Item2.ToString()}).
    ToList();

Hopefully this also helps you think differently about this kind of data processing. If an IEnumerable with typed data is so much more efficient that we use it as an intermediate step anyway, then its probably also the better way to handle passing the data between methods or classes in the first place. At minimum, you can at least start thinking about removing the .ToList() from the end of these lines, since you can always append it to a variable when passing it to a function that still really needs a list.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading