簡單的鍵值按值排序問題
需求是這樣的:http://q.cnblogs.com/q/29266/
這里簡述一下:
一個小小排序問題。。不是很高深的
用c#代碼實現,不要用linq技術
問題:
廣東 30
湖南 20
廣西 60
北京 70
上海 30
排序之后:
北京 70
廣西 60
廣東 30
上海 30
湖南 20
這是一個簡單的鍵值按值排序問題,難點在于不用linq(有的項目環境是.NET 2.0),如果用linq很容易解決(在該問題的回復中有,這里就不說了),下面提供兩種方法。
方法一,建一個只有key和value兩個屬性的實體,然后用冒泡排序,代碼如下:
class Program
{
static void Main(string[] args)
{
List<TestModel> tmlist = new List<TestModel>()
{
new TestModel(){city="廣東",count=30},
new TestModel(){city="湖南",count=20},
new TestModel(){city="廣西",count=60},
new TestModel(){city="北京",count=70},
new TestModel(){city="上海",count=30}
};
TestModel temp = new TestModel();
for (int m = 0; m < tmlist.Count; m++)
{
for (int n = 0; n < tmlist.Count - m - 1; n++)
{
if (tmlist[n].count < tmlist[n + 1].count)
{
temp = tmlist[n];
tmlist[n] = tmlist[n + 1];
tmlist[n + 1] = temp;
}
}
}
foreach (var item in tmlist)
{
Console.WriteLine(item.city + "" + item.count);
}
Console.Read();
}
}
public class TestModel
{
public string city { get; set; }
public int count { get; set; }
}
這種方法容易理解,但要新建一個實體比較麻煩。
如果在程序中只要做個簡單的排序這樣就顯得太復雜了,有沒有簡單的方法呢?我這里提供另外一種思路,代碼如下:
class Program
{
static void Main(string[] args)
{
//原有數據
Dictionary<string, int> val = new Dictionary<string, int>();
val.Add("廣東",30);
val.Add("湖南",20);
val.Add("廣西",60);
val.Add("北京",70);
val.Add("上海",30);
SortedDictionary<int, string> newval = new SortedDictionary<int, string>(new ReverseComparer<int>());
int index = 1;
foreach (var item in val)
{
//這一行是關鍵
newval.Add(item.Value * 1000+index, item.Key);
index++;
}
val = new Dictionary<string, int>();
foreach (var item in newval)
{
val.Add(item.Value, item.Key / 1000);
Console.WriteLine(item.Value + "" + item.Key/1000);
}
//val就是排序后的字典集合
Console.Read();
}
}
sealed class ReverseComparer<T> : IComparer<T> where T : IComparable<T>
{
public int Compare(T x, T y)
{
return y.CompareTo(x);
}
}
程序中也說了,newval.Add(item.Value * 1000+index, item.Key);這一行是關鍵,各位讀者自己思考一下為什么可以這樣處理,這樣處理有什么局限性。
非常歡迎大家提出自己的看法,留言討論。

浙公網安備 33010602011771號