简体   繁体   中英

Items being added into sorted list in wrong order

I'm adding a list of values into a sorted list. The problem is that it's not adding the data into my sorted list correctly.

public static void newList(List<string> oldList, List<string> headers)
    {
        var noHeaders = removeHeaders(oldList, headers);

        SortedList<string, string> newList = new SortedList<string, string>();
        for (int i = 0; i < headers.Count; i++)
        {
            newList.Add(headers[i], "placeholder");
        }

            //foreach (string header in headers)
            //{
            //    newList.Add(header, "placeholder");
            //}

Above is a snippet of my code, I've tried all different kinds of loops with the same result.

The data from the "headers" list looks like this:

[0]Value1
[1]Value2
[2]Value3
[3]Value4

When I look at the same data once it's been added into the sorted list it looks like this:

[0]Value2
[1]Value1
[2]Value4
[3]Value3

Can anybody explain to me why this is happening so that I can fix it? I've searched around for a bit but couldn't find anything helpful.

Thanks

According to this documentation , the entries of the list are sorted with respect to the keys , not the values ; this means that the order you observe depends on the values provided in headers and the values as such are not sorted.

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