我无法使用字符串对列表进行排序

时间:2019-10-20 11:59:48

标签: c# sorting listbox

我现在可以像这样对列表进行排序:

_personList = _personList.OrderBy(l => l.Name).ToList();

如果我想使用lambda,

但是出于培训目的,我想使用委托比较器。

我的代码:

    public class Person : IEquatable<Person>, IComparable<Person>
    {
        public Person(string name,int age, string interest)
        {
            _name = name;
            _age = age;
            _interest = interest;

        }

        private string _name = string.Empty;
        private int _age = 0;
        private string _interest = string.Empty;
        private string _cmbShowText = string.Empty;



        public string Name
        {
            get { return _name; }
            set {_name = value; }
        }
   //Left out some not interesting properties//

        public bool Equals(Person other)
        {
            if (other == null) return false;
            return (this.Name.Equals(other.Name));
        }

        public int CompareTo(Person other)
        {
            // A null value means that this object is greater.
            if (other == null)
                return 1;

            else
                return this.Name.CompareTo(other.Name);
        }
    }

排序方法:(lstall是一个列表框)

private void CmdSortCustom_Click(object sender, EventArgs e)
{               //Avancerad sortering
                _personList.Sort(delegate (Person x, Person y)
                {
                    if (x.Name == null && y.Name == null) return 0;
                    else if (x.Name == null) return -1;
                    else if (y.Name == null) return 1;
                    else return x.Name.CompareTo(y.Name);
                });

    reFreshDatasource();
}
    private void reFreshDatasource()
{
    lstall.DisplayMember = "Name";
    lstall.ValueMember = "Name";
    lstall.DataSource = _personList;
}

按字母顺序对名称进行排序是怎么回事?

代码符合,程序不会崩溃。

1 个答案:

答案 0 :(得分:0)

就像@ Jesse de Wit-告诉我,我首先将数据源设置为NULL。