我有一个包含
A、15
B、67
C、45
D、10的文件
我正在从文件中读取数据,但我想将数据读入字典或哈希表,但数据应按其值
B、67
C、45
A、15
D.10排序到其中
如果任何其他列表将作为有效的方式工作,请建议
谢谢
我有一个包含
A、15
B、67
C、45
D、10的文件
我正在从文件中读取数据,但我想将数据读入字典或哈希表,但数据应按其值
B、67
C、45
A、15
D.10排序到其中
如果任何其他列表将作为有效的方式工作,请建议
谢谢
A Dictionary<,>
/Hashtable
没有定义的排序;那不管用。ASortedDictionary<,>
是按key排序的,而不是按value排序的,所以这是行不通的。就个人而言,我认为你应该只使用一个常规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; }
}
或者,使用 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;
}
}
您确定需要将其存储在字典中吗?通常,当您使用字典时,您需要快速访问给定键的项目,但您不太关心内部排序。所以你可能需要重新考虑你的数据结构。
无论如何,如果您想访问按值排序的字典中的数据,您可以使用 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);