我有一个包含如下内容的文件
答:15
B,67
C,45
D,10
我正在从文件中读取数据,但我想将数据读取到字典或哈希表中,但数据应该按其值进行排序,即
B,67
C,45
答:15
D.10
如果有任何其他列表可以作为有效的工作方式,请建议
谢谢
发布于 2011-07-22 14:14:43
Dictionary<,>/Hashtable没有定义的排序;这将不起作用。SortedDictionary<,>是按键排序的,而不是按值排序的,所以这是行不通的。就我个人而言,我认为你应该只使用一个常规的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-22 15:16:40
或者,使用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-22 15:40:26
您确定需要将其存储在字典中吗?通常,当您使用字典时,您需要快速访问给定关键字的项,但您并不太关心内部排序。因此,您可能需要重新考虑您的数据结构。
无论如何,如果您想访问按值排序的字典中的数据,可以使用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); https://stackoverflow.com/questions/6786276
复制相似问题