c# - 当列表计数为 "0"时插入到列表中

标签 c# .net wpf generic-list

这是我的代码

public class ControlProperty
{        
    public int SortOrder { get; set; }
    public string DisplayName { get; set; }
}

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        ControlProperty ct = new ControlProperty();
        ControlProperty ct1 = new ControlProperty();
        List<ControlProperty> lstct = new List<ControlProperty>();
        ct.DisplayName = "test";
        ct1.DisplayName = "test1";
        ct1.SortOrder = 1;
        ct.SortOrder = 0;
        lstct.Insert(ct1.SortOrder, ct1);
        lstct.Insert(ct.SortOrder, ct);
        lstbxIncidentControls.ItemsSource = lstct;

    }
}

我在这里尝试将列表(根据排序顺序)项目插入到计数为零且不能像那样插入的列表对象中....

所以我想根据我的排序顺序插入到列表中....

谁能帮我解决这个问题

最佳答案

使用列表的.Add函数

List<string> mylist = new List<string>();
mylist.Add("firstvalue");
mylist.Add("secondvalue");

string getsecondvalue = mylist[1];//remember it starts at 0 so the first entry is mylist[0]

这是一个如何使用.Insert函数的例子
也就是说,如果列表没有插入任何值,这将起作用(mylist.Count = 0)

mylist.Insert(0, "inserted");

如果您的列表没有值 (mylist.Count = 0) 而您尝试

mylist.Insert(1, "inserted");

它会中断,因为它没有值可以添加到位置 0
如果 mylist 中有数据,它会将其插入位置 1(按指定) 并将其余的向上移动,即 1->22->33->4 等等

关于c# - 当列表计数为 "0"时插入到列表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38975648/

相关文章:

c# - OleDB 无法确定十进制值

c# - 在 MVVM 菜单中绑定(bind) HeaderTemplate

c# - 使用进程间同步对象同步 2 个进程 - Mutex 或 AutoResetEvent

c# - 只执行程序的一部分

c# - 如何在 WPF 中居中对齐组合框所选项目

.net - 接口(interface)不应该有属性吗?

c# - Entity Framework ,我可以将一个类映射到一个键/值表吗?

c# - 使 TabControl 宽度等于最大 TabItems 宽度和高度

c# - 在itextsharp中为pdfpcell添加圆形颜色边框

c# - 什么是最简单,正确的年龄计算方法?