【问题标题】:Insert into List when list Count is "0"当列表计数为“0”时插入列表
【发布时间】:2016-08-16 12:58:35
【问题描述】:

这是我的代码

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;

    }
}

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

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

谁能帮我解决这个问题

【问题讨论】:

  • list.add 伙计。使用 add 方法。
  • 如果你使用Insert,第一个参数是你想要定位的列表中的索引。您不能使用SortOrder,因为这与列表中的索引没有任何关系
  • @EdPlunkett 不必要的讽刺
  • 我喜欢这种讽刺,这是我给出答案的唯一原因,它让我发笑,所以我有足够的幸福来回答这样一个愚蠢的问题 XD
  • @JayMEE 虽然没必要,但很搞笑。

标签: c# .net wpf generic-list


【解决方案1】:

使用列表的.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-&gt;22-&gt;33-&gt;4 等等

【讨论】:

    【解决方案2】:

    添加一个包装函数,条件是如果索引大于List的大小,它将被添加到它的末尾。

      public static void OrderIndex(List<ControlProperty> lControlProperty, ControlProperty controlProperty, int index)
        {
            if (lControlProperty.Count < index)
            {
                lControlProperty.Add(controlProperty);
            }
            else
            {
                lControlProperty.Insert(index, controlProperty);
            }
        }
    

    这样称呼它:

     OrderIndex(lstct, ct1, ct1.SortOrder);
     OrderIndex(lstct, ct, ct.SortOrder);
    

    【讨论】:

      【解决方案3】:

      这是一个 ControlProperty 列表

      lstct.Add(ct);  
      lstct.Add(ct1);  
      

      或清洁剂

      public class ControlProperty
      {        
          public int SortOrder { get; set; }
          public string DisplayName { get; set; }
          public ControlProperty (int sortOrder, string displayName) 
          {
              SortOrder = sortOrder;
              DisplayName = displayName;
          }
      }
      
      lstct.Add(new ControlProperty(0, "text0");
      lstct.Add(new ControlProperty(1, "text1");
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-11-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-05-14
        • 2013-04-22
        相关资源
        最近更新 更多