【问题标题】:Winforms displaying information from dictionary in a Listbox (sorting by value)Winforms 在列表框中显示字典中的信息(按值排序)
【发布时间】:2013-04-21 15:56:22
【问题描述】:

所以,我有一个排序字典,其中我的键是名字,值是姓氏。

我的表单上有一个列表框,其中显示了用户可以从中选择姓氏的所有可能值。但是,由于名字是键,因此列表框中显示的这些值没有排序。

Andrews -> Carter -> Johnson

Carter -> Johnson -> Andrews

我希望姓氏按照第一行中的字母顺序排列,而不是现在的方式(第二行)。

创建一个只包含值的列表是最好的方法吗?我找不到任何方法对 ListBox 的内容进行内部排序,所以我不知道还能做什么。

【问题讨论】:

  • 您可以在填充列表框之前简单地对字典进行排序。你必须使用 LINQ 来做到这一点:myDict.OrderBy(x => x.Key);

标签: c# winforms dictionary listbox


【解决方案1】:

您可以按正确的顺序创建另一个列表,例如:

// Given that 'Person' for the sake of this example is:

public class Person
{
    public string FirstName;
    public string LastName;
}

// And you have a dictionary sorted by Person.FirstName:

var dict = new SortedDictionary<string, Person>();
// ...initialise dict...

// Make list reference a List<Person> ordered by the person's LastName

var list = (from entry in dict
            orderby entry.Value.LastName
            select entry.Value).ToList();

// Use list to populate the listbox

这样做的好处是不修改原始集合(如果这对您很重要)。

将对象引用保存在两个不同集合中的开销不是很高,因为每个对象只有一个引用(加上List&lt;&gt; 实现本身的一些固定开销)。

但请记住,只要其中一个集合还活着,对象就会一直保持活跃(除非您明确清除集合)。


可编译示例:

using System;
using System.Collections.Generic;
using System.Linq;

namespace Demo
{
    public static class Program
    {
        private static void Main()
        {
            dict = new SortedDictionary<string, Person>();

            addPerson("iain", "banks");
            addPerson("peter", "hamilton");
            addPerson("douglas", "adams");
            addPerson("arthur", "clark");
            addPerson("isaac", "asimov");

            Console.WriteLine("--------------");

            foreach (var person in dict)
                Console.WriteLine(person.Value);

            var list = (from entry in dict
                        orderby entry.Value.LastName
                        select entry.Value).ToList();

            Console.WriteLine("--------------");

            foreach (var person in list)
                Console.WriteLine(person);
        }

        private static void addPerson(string firstname, string lastname)
        {
            dict.Add(firstname, new Person{FirstName = firstname, LastName = lastname});
        }

        private static SortedDictionary<string, Person> dict;
    }

    public class Person
    {
        public string FirstName;
        public string LastName;
        public override string ToString(){return FirstName + " " + LastName;}
    }
}

【讨论】:

    猜你喜欢
    • 2012-04-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-17
    • 1970-01-01
    • 2019-05-10
    • 1970-01-01
    • 2022-01-15
    相关资源
    最近更新 更多