1


A、15
B、67
C、45
D、10として含むファイルがあります

ファイルからデータを読み取っていますが、データを辞書またはハッシュテーブルに読み取りたいのですが、データは
B、67
C、45
A、
15D.10の値で並べ替える必要があります。

他のリストが効率的に機能する場合は、提案してください

ありがとう

4

3 に答える 3

5

Dictionary<,>/Hashtableにはソートが定義されていません。それは機能しません。AはではなくキーSortedDictionary<,>でソートされるため、機能しません。個人的には、通常の(2つのプロパティを持つ単純なもの)を使用する必要があると思います。ロードした後は、次のようにします。List<T>T

list.Sort((x,y) => y.SecondProp.CompareTo(x.SecondProp));

そこにある微妙な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; }
}
于 2011-07-22T06:14:42.603 に答える
0

または、IComparable<>を使用します

完全な例:

 public class Program
    {
        public static void Main(string[] args)
        {
            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 });

            list.Sort();           
        }
    }


    internal class MyData : IComparable<MyData>
    {
        public string Key { get; set; }
        public int Value { get; set; }
        public int CompareTo(MyData other)
        {
            return other.Value.CompareTo(Value);
        }

        public override string ToString()
        {
            return Key + ":" + Value;
        }
    } 
于 2011-07-22T07:16:40.017 に答える
0

辞書に保存する必要がありますか?通常、辞書を使用する場合は、キーが指定されたアイテムにすばやくアクセスする必要がありますが、内部の順序についてはあまり気にしません。したがって、データ構造を再考する必要があるかもしれません。

とにかく、値順に並べられたディクショナリのデータにアクセスする場合は、LINQクエリを使用できます。

Dictionary<string, int> data = new Dictionary<string, int>();
data.Add("A", 15);
data.Add("B", 67);
data.Add("C", 45);
data.Add("D", 10);

var ordered = (from d in data
                orderby d.Value
                select new Tuple<string, int>(d.Key, d.Value));

foreach (var o in ordered)
    Console.WriteLine(o.Item1 + "," + o.Item2);            
于 2011-07-22T07:40:26.177 に答える