Dictionary<int, string> dic = new Dictionary<int, string>();
dic.Add(1, "HaHa");
dic.Add(5, "HoHo");
dic.Add(3, "HeHe");
dic.Add(2, "HiHi");
dic.Add(4, "HuHu");
var result = from pair in dic orderby pair.Key select pair;
foreach (KeyValuePair<int, string> pair in result)
{
Console.WriteLine("Key:{0}, Value:{1}", pair.Key, pair.Value);
}
// 根据最大Vlue和最小value取对应的Key
private void button1_Click(object sender, EventArgs e)
{
List<string> list = new List<string>();
Dictionary<string, string> dic = new Dictionary<string, string>();
dic.Add("[1]", "02:01:11");
dic.Add("[2]", "03:01:11");
dic.Add("[3]", "01:01:13");
list.Add("02:01:11");
list.Add("03:01:11");
list.Add("01:01:13");
list.Sort();
string minKey= GetKey(dic,list[0]);
string maxKey = GetKey(dic, list[list.Count-1]);
MessageBox.Show("min:" + minKey + list[0] + System.Environment.NewLine + "max:" + maxKey + list[list.Count - 1]);
}
// 根据Value取Key值
private string GetKey(Dictionary<string,string> dic, string value)
{
string str="";
var key = from d in dic
where d.Value == value
select d.Key;
foreach (var k in key)
{
str = str + k +",";
}
return str.TrimEnd(',');
//如果没有重复项可直接查找
var str2 = dic.SingleOrDefault(k => k.Value == value);
// Dictionary排序
var result = dic.OrderByDescending((s) => s.Value);
var result2 = dic.OrderByDescending((s) => s.Key);
}
// 应用实例
private void button1_Click(object sender, EventArgs e) { List<person> per = new List<person> { new person{ Name="AB", Age=30}, new person{ Name="AA", Age=12}, new person{ Name="AA", Age=13} };
var result = per.Where(p => p.Name == "AB") .OrderByDescending(p => p.Age) .Take(2); //从序列的开头返回指定数量的连续元素。 foreach (var r in result) { MessageBox.Show(r.Age.ToString()); }
}
public class person { public string Name { get; set; } public int Age { get; set; } }