How to sort in a dictionary object

I am working with a Dictionary object in C #. I have all kinds of data, but now I would like to sort it in ascending order, given a certain value (double).

How is the dictionary defined:

Dictionary<int, Dictionary<string, string>> myDict = getDictData(nr);

Here's what the Dictionary looks like:

myDict[0]{"name", "name1"}
myDict[0]{"number", 0.0158}

myDict[1]{"name", "name2"}
myDict[1]{"number", 0.0038}

myDict[2]{"name", "name3"}
myDict[2]{"number", 0.0148}

I do not know if I will do it right to clear, I call the name name2 as follows:

myDict[1]["name"]

So, I want to sort this object so that the first (myDict [0]) contains the object with the smallest value "number".

I tried looking on the Internet, but all I can find is to arrange this by the first key / value, which, of course, is null myDict [0].

As you know, I have not gone far. So maybe you can help me a little.

This is what I have tried so far:

foreach (var item in myDict.OrderBy(i => i.Key))
{
      Console.WriteLine(item);
}

or that:

var items = from pair in myDict orderby pair.Value ascending select pair;

or that:   myDict .Sort((x, y) => x.waterDepth.CompareTo(y.waterDepth));

nothing succeeded...

+4
3

A Dictionary<TKey, TValue> . , .

SortedDictionary, , .

, :

using System;
using System.Collections.Generic;

namespace ConsoleApplication2
{
    using StrStrDict = Dictionary<string, string>;

    public sealed class CustomComparer: IComparer<StrStrDict>
    {
        public int Compare(StrStrDict lhs, StrStrDict rhs)
        {
            double x = Double.Parse(lhs["number"]);
            double y = Double.Parse(rhs["number"]);

            return x.CompareTo(y);
        }
    }

    internal class Program
    {
        private static void Main()
        {
            var dict1 = new StrStrDict
            {
                {"name",   "name1"},
                {"number", "0.0158"}
            };

            var dict2 = new StrStrDict
            {
                {"name",   "name2"},
                {"number", "0.0038"}
            };

            var dict3 = new StrStrDict
            {
                {"name",   "name3"},
                {"number", "0.0148"}
            };

            var list = new List<StrStrDict> {dict1, dict2, dict3};

            list.Sort(new CustomComparer());

            foreach (var element in list)
            {
                Console.WriteLine("Number = " + element["number"]);
            }
        }
    }
}

, , , , , , , Dictionary<string, string>. . , Dictionary<string, object> - . .

, !

Dictionary<string, object>:

using System;
using System.Collections.Generic;

namespace ConsoleApplication2
{
    using StrObjDict = Dictionary<string, object>;

    public sealed class CustomComparer: IComparer<StrObjDict>
    {
        public int Compare(StrObjDict lhs, StrObjDict rhs)
        {
            double x = (double)lhs["number"];
            double y = (double)rhs["number"];

            return x.CompareTo(y);
        }
    }

    internal class Program
    {
        private static void Main()
        {
            var dict1 = new StrObjDict
            {
                {"name",   "name1"},
                {"number", 0.0158}
            };

            var dict2 = new StrObjDict
            {
                {"name",   "name2"},
                {"number", 0.0038}
            };

            var dict3 = new StrObjDict
            {
                {"name",   "name3"},
                {"number", 0.0148}
            };

            var list = new List<StrObjDict> {dict1, dict2, dict3};

            list.Sort(new CustomComparer());

            foreach (var element in list)
            {
                Console.WriteLine("Name = {0}, Number = {1}", element["name"], element["number"]);
            }
        }
    }
}

, , , . "" "" , , !

: , ( !):

using System;
using System.Collections.Generic;

namespace ConsoleApplication2
{
    public sealed class Entry
    {
        public readonly string Name;
        public readonly double Number;

        public Entry(string name, double number)
        {
            Name   = name;
            Number = number;
        }
    }

    internal class Program
    {
        private static void Main()
        {
            var list = new List<Entry>
            {
                new Entry("name1", 0.0158),
                new Entry("name2", 0.0038),
                new Entry("name3", 0.0148)
            };

            list.Sort((lhs, rhs) => lhs.Number.CompareTo(rhs.Number));

            // Alternatively if you don't want an in-place sort and you
            // want to keep the original unsorted list, you can create
            // a separate sorted list using Linq like so:
            //
            // var sortedList = list.OrderBy(x => x.Number).ToList();

            foreach (var element in list)
            {
                Console.WriteLine("Name = {0}, Number = {1}", element.Name, element.Number);
            }
        }
    }
}
+4

, , List<Dictionary<string, string>>.
List, , int Dictionary<string, string> List " , " .
:

        List<Dictionary<string, string>> myDict = new List<Dictionary<string, string>>();
        myDict.Add(new Dictionary<string, string>());
        myDict.Add(new Dictionary<string, string>());
        myDict.Add(new Dictionary<string, string>());
        myDict[0].Add("name", "name1");
        myDict[0].Add("number", "0.0158");
        myDict[1].Add("name", "name2");
        myDict[1].Add("number", "0.0038");
        myDict[2].Add("name", "name3");
        myDict[2].Add("number", "0.0148");

        var result = myDict.SelectMany(x => x.Where(d => d.Key == "number")).OrderBy(x => x.Value);

- . , :

class Foo
{
    public string Name { get; set; }
    public double Number { get; set; }
}

List<Foo> myDict = new List<Foo>();
myDict.Add(new Foo() { Name = "name1", Number = 0.0158 });
myDict.Add(new Foo() { Name = "name2", Number = 0.0038 });
myDict.Add(new Foo() { Name = "name3", Number = 0.0148 });
var result = myDict.OrderBy(x => x.Number);
+3

, , , (myDict [0]) "".

, , , , , , .

0, 1, 2…, :

myDict = myDict.Values
    .OrderBy(val => double.Parse(val["number"]))
    .Select((val, idx) => new{Key = idx, Value = val})
    .ToDictionary(pair => pair.Key, pair => pair.Value);

, , (0, 1, …), .

, , myDict = myDict.Values.OrderBy(val => double.Parse(val["number"])).ToList() . , , .

( 0, 1, 2…, , , , :

myDict = myDict.Values
    .OrderBy(val => double.Parse(val["number"]))
    .Zip(myDict.Keys.OrderBy(key => key), (val, key) => new{Key = key, Value = val})
    .ToDictionary(pair => pair.Key, pair => pair.Value);

This takes values ​​and orders them as described above, but then it takes the keys separately and orders them before combining them again and creating a new dictionary with it.

+2
source

All Articles