在从文件读取数据时将排序数据添加到哈希表或字典中

usr*_*986 1 c# collections generic-collections

我有一个包含
A,15
B,67
C,45
D,10的文件

我正在从文件中读取数据,但我想将数据读入字典或散列表,但数据可以通过其值
B,67
C,45
A,15
D.10进行分类.

如果任何其他列表将以有效的方式工作,请建议

谢谢

Mar*_*ell 5

A Dictionary<,>/ Hashtable没有定义的排序; 那样不行.A 按键SortedDictionary<,>排序,而不是按排序,因此不起作用.就个人而言,我认为你应该只使用常规(对于一些简单的两个属性),并在加载后:List<T>T

list.Sort((x,y) => y.SecondProp.CompareTo(x.SecondProp));
Run Code Online (Sandbox Code Playgroud)

那里微妙的x/y开关实现了"下降".如果您还需要第一个属性键入的数据,则单独存储一个Dictionary<string,int>.

完整示例:

class Program
{
    static void Main()
    {
        List<MyData> list = new List<MyData>();
        // load the data (replace this with a loop over the file)
        list.Add(new MyData { Key = "B", Value = 67 });
        list.Add(new MyData { Key = "C", Value = 45 });
        list.Add(new MyData { Key = "A", Value = 15 });
        list.Add(new MyData { Key = "D", Value = 10 });
        // sort it
        list.Sort((x,y)=> y.Value.CompareTo((x.Value)));
        // show that it is sorted
        foreach(var item in list)
        {
            Console.WriteLine("{0}={1}", item.Key, item.Value);

        }
    }
}

internal class MyData
{
    public string Key { get; set; }
    public int Value { get; set; }
}
Run Code Online (Sandbox Code Playgroud)