数据字典中值的排序

风一样的大叔 2011-12-29 03:30:05

Dictionary<string,int> NewLengths = new Dictionary<string,int>();
for (int n = 0; n < tableArray.Length - 1; n++)
{
for (int u = 0; u < TableLengths.Count; u++)
{
if (TableLengths[u].Name == tableArray[n])
{
NewLengths.Add(TableLengths[u].Name,TableLengths[u].Length);
}
}
}

NewLengths的值为:
"aaa",3
"ddd",4
"fff",2
"rrr",1

我现在要将这个数据字典按照value值排序,即为
"rrr",1
"fff",2
"aaa",3
"ddd",4
最后的保存形式可以为数据字典,不行的话为List也行啊,求怎么排序呢


...全文
394 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
风一样的大叔 2011-12-29
  • 打赏
  • 举报
回复
问题解决了
 var list = (from d in Lengths orderby d.Value ascending select d).ToList();//对数据字典进行排序
这样默认是按升序排序的
  • 打赏
  • 举报
回复


class Program
{
static int keySelector(KeyValuePair<string, int> entry)
{
return entry.Value;
}

static void Main()
{
Dictionary<string, int> vals = new Dictionary<string, int>();
vals.Add("asp.net", 3);
vals.Add("vb.net", 2);
vals.Add("html5", 1);

IOrderedEnumerable<KeyValuePair<string, int>> result = vals.OrderBy(keySelector);

foreach (var item in result)
Console.WriteLine("{0}:{1}", item.Key, item.Value);

}
}

vrhero 2011-12-29
  • 打赏
  • 举报
回复
字典无序,现排即可....

NewLengths.OrderBy(o=>o.Value)

如果集合很大,你应该用其他数据结构...
风一样的大叔 2011-12-29
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 kkxxllasasas 的回复:]
http://hi.baidu.com/pctonc/blog/item/6db3a2fb4b7e8c8d59ee90db.html
[/Quote]试了下.貌似不行啊,没变化
stonespace 2011-12-29
  • 打赏
  • 举报
回复
放到List里,用List.Sort排序,效率最高,
杨友山 2011-12-29
  • 打赏
  • 举报
回复

string[] itemList =new string[] { "x=10", "y=5", "k=4", "r=9" };
int flag = 1;

int i, j;

int itemCount = itemList.Length;

string itemTemp;

for (i = 1; i < itemCount && flag == 1; i++)
{
flag = 0;

for (j = 0; j < itemCount - i; j++)
{
string itemfore = itemList[j];

int countfore = Convert.ToInt32(itemfore.Substring(itemfore.IndexOf('=') + 1, itemfore.Length - (itemfore.IndexOf('=') + 1)));

string itemback = itemList[j + 1];

int countback = Convert.ToInt32(itemback.Substring(itemback.IndexOf('=') + 1, itemback.Length - (itemback.IndexOf('=') + 1)));

if (countfore < countback)
{
flag = 1;

itemTemp = itemList[j];

itemList[j] = itemList[j + 1];

itemList[j + 1] = itemTemp;
}
}
}
return itemList;
}

这是我曾经用到的一个排序。

110,539

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧