[英]How to populate a listbox sorted with unsorted array
我有一系列具有两个属性(名称和位置)的项目。 该数组没有以任何方式排序,我想按位置顺序填充一个列表框。
我可以使用下面的代码来做到这一点,首先添加所有项目,这样我便获得了一个列表,其中列出了正确数量的项目,然后在正确位置替换了这些项目。 但是我想知道是否有更好的方法呢?
我希望列表框具有以下名称:Mark,John和James。
注意:James,Mark和John数据只是一个例子,我无法对常规数组进行排序。
public class _standing
{
public _standing(string _name, int _pos) {
name = _name;
position = _pos;
}
public string name { get; set; }
public int position { get; set; }
}
_standing a = new _standing("James", 2);
_standing b = new _standing("Mark", 0);
_standing c = new _standing("John", 1);
_standing[] standing = new _standing[]{a, b, c};
for (int i = 0; i < standing.Length; i++) {
listBox1.Items.Add(standing[i].name);
}
for (int i = 0; i < standing.Length; i++) {
listBox1.Items.RemoveAt(standing[i].position);
listBox1.Items.Insert(standing[i].position, standing[i].name);
}
您可以只使用数组的OrderBy
方法:
standing = standing.OrderBy(i => i.position).ToArray();
listBox1.Items.AddRange(standing);
您也可以按降序排列:
standing.OrderByDescending(i => i.position).ToArray();
这些都需要引用System.Linq
另外,由于OrderBy
返回了新对象,因此您也可以执行此操作而无需重新排序原始列表:
_standing a = new _standing("James", 2);
_standing b = new _standing("Mark", 0);
_standing c = new _standing("John", 1);
_standing[] standing = new _standing[] { a, b, c };
listBox1.Items.AddRange(standing.OrderBy(i => i.position).ToArray());
更新
为了在listBox1中显示有意义的内容,您应该在_standing类上重写ToString
方法,例如:
public class _standing
{
public string name { get; set; }
public int position { get; set; }
public _standing(string _name, int _pos)
{
name = _name;
position = _pos;
}
public override string ToString()
{
return position + ": " + name;
}
}
最后,我不得不提到您的大小写/命名约定不是标准的C#。 该标准的目的是将类和属性设置为PascalCase,将参数设置为camelCase,将私有字段设置为带有可选下划线前缀的pascalCase。 因此,理想情况下,您的代码应类似于:
public class Standing
{
public string Name { get; set; }
public int Position { get; set; }
public Standing(string name, int position)
{
Name = name;
Position = position;
}
public override string ToString()
{
return Position + ": " + Name;
}
}
和...
Standing a = new Standing("James", 2);
Standing b = new Standing("Mark", 0);
Standing c = new Standing("John", 1);
Standing[] standing = { a, b, c };
listBox1.Items.AddRange(standing.OrderBy(i => i.Position).ToArray());
如果您是我,我会先创建一个_standing列表并添加到列表中。 就像是:
List<_standing> standingList = new List<_standing>();
standingList.Add(new _standing("James", 2));
etc...
使用List而不是数组类型的优点是它的大小是动态的。 如果您只打算拥有3个_standing对象,那么数组就可以了,但实际上可能不太可能。
然后,您可以使用Linq查询按位置对列表进行排序
IEnumerable<_standing> sorted = standingList.OrderBy(stand => stand.Position);
现在,您已经拥有使用.NET内置排序算法的排序列表,可以将其添加到控件Items集合中。 您可以使用AddRange方法节省时间:
listBox1.Items.AddRange(sorted);
供参考的来源:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.