简单的键值按值排序问题

  需求是这样的: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);这一行是关键,各位读者自己思考一下为什么可以这样处理,这样处理有什么局限性。

  非常欢迎大家提出自己的看法,留言讨论。

posted @ 2011-10-28 10:22  artwl  阅读(1183)  评论(0编辑  收藏  举报

个人简介

var ME = {
	"name": "土豆/Artwl",
	"job": "coding",
	"languages": [
		"JS", "HTML",
                "CSS", "jQuery"
		"MVC",".NET",
		"设计模式"
	],
	"hobby": [
		"阅读", "旅游",
		"音乐", "电影"
	]
}
TOP