对名称值集合进行排序

发布于 2024-09-30 20:36:37 字数 108 浏览 0 评论 0原文

如何按字母顺序对名称值集合进行排序?我是否必须先将其转换为另一个列表,例如排序列表或 Ilist 或其他列表?如果那么我该怎么做?现在我的所有字符串都在 namevaluecollection 变量中。

How do I sort a namevaluecollection in alphabetical order? Do I have to cast it to another list first like the sorted list or Ilist or something? If then how do I do that? right now I have all my string in the the namevalucollection variable.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

筑梦 2024-10-07 20:36:37

如果您手中有合适的集合,最好先使用它。但是,如果您必须对 NameValueCollection 进行操作,这里有一些不同的选项:

NameValueCollection col = new NameValueCollection();
col.Add("red", "rouge");
col.Add("green", "verde");
col.Add("blue", "azul");

// order the keys
foreach (var item in col.AllKeys.OrderBy(k => k))
{
    Console.WriteLine("{0}:{1}", item, col[item]);
}

// or convert it to a dictionary and get it as a SortedList
var sortedList = new SortedList(col.AllKeys.ToDictionary(k => k, k => col[k]));
for (int i = 0; i < sortedList.Count; i++)
{
    Console.WriteLine("{0}:{1}", sortedList.GetKey(i), sortedList.GetByIndex(i));
}

// or as a SortedDictionary
var sortedDict = new SortedDictionary<string, string>(col.AllKeys.ToDictionary(k => k, k => col[k]));
foreach (var item in sortedDict)
{
    Console.WriteLine("{0}:{1}", item.Key, item.Value);
}

Preferably use a suitable collection to begin with if it's in your hands. However, if you have to operate on the NameValueCollection here are some different options:

NameValueCollection col = new NameValueCollection();
col.Add("red", "rouge");
col.Add("green", "verde");
col.Add("blue", "azul");

// order the keys
foreach (var item in col.AllKeys.OrderBy(k => k))
{
    Console.WriteLine("{0}:{1}", item, col[item]);
}

// or convert it to a dictionary and get it as a SortedList
var sortedList = new SortedList(col.AllKeys.ToDictionary(k => k, k => col[k]));
for (int i = 0; i < sortedList.Count; i++)
{
    Console.WriteLine("{0}:{1}", sortedList.GetKey(i), sortedList.GetByIndex(i));
}

// or as a SortedDictionary
var sortedDict = new SortedDictionary<string, string>(col.AllKeys.ToDictionary(k => k, k => col[k]));
foreach (var item in sortedDict)
{
    Console.WriteLine("{0}:{1}", item.Key, item.Value);
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文