.net 如何将项目添加到ICollection中的特定索引中?

.net 如何将项目添加到ICollection中的特定索引中?,.net,wpf,list,c#-4.0,collections,.net,Wpf,List,C# 4.0,Collections,代码: TestItem TI=newtestitem(); ITestItem IC=TI; 对照组。试验项目。添加(IC)//这会将该项添加到最后一列中,但我需要将其添加到特定索引中 测试是一门课程 ITestItem是一个接口 控件是一个局部变量 TestItems是一个ICollection 如何将项目添加到ICollection中的特定索引中?ICollection没有允许在指定索引位置插入的插入方法 相反,您可以使用具有insert方法的IList: TestItem TI = n

代码:

TestItem TI=newtestitem();
ITestItem IC=TI;
对照组。试验项目。添加(IC)//这会将该项添加到最后一列中,但我需要将其添加到特定索引中
测试是一门课程
ITestItem是一个接口
控件是一个局部变量
TestItems是一个ICollection
如何将项目添加到ICollection中的特定索引中?

ICollection没有允许在指定索引位置插入的插入方法

相反,您可以使用具有insert方法的
IList

TestItem TI = new TestItem();
ITestItem IC = TI;
controls.TestItems.Add(IC); //This adds the item into the last column, but I need to add this in a particular index

TestItem is a Class  
ITestItem is an Interface 
controls is a local variable
TestItems is a ICollection<ITestItem>
您可以这样使用:

void Insert(int index, T item);

如果可以避免的话,我不建议您这样做,但是这里有一个
Insert
扩展方法的可能实现,用于
ICollection

controls.TestItems.Insert(4, IC);
publicstaticvoidaddrange(此ICollection集合,IEnumerable项){
如果(集合是列表){
列表。添加范围(项目);
}
否则{
foreach(项目中的T项目)
集合。添加(项目);
}
}
公共静态void Insert(此ICollection集合,int索引,T项){
如果(索引<0 | |索引>集合.计数)
抛出新ArgumentOutOfRangeException(nameof(index),“索引超出范围。必须为非负且小于集合的大小。”);
如果(集合是IList列表){
列表。插入(索引,项目);
}
否则{
列表温度=新列表(集合);
collection.Clear();
collection.AddRange(temp.Take(index));
集合。添加(项目);
collection.AddRange(临时跳过(索引));
}
}
在调用
Clear
Add
时,请注意潜在的副作用。这也是非常低效的,因为它需要清除
ICollection
并重新添加所有项,但有时在危急时刻需要采取紧急措施

public static void AddRange<T>(this ICollection<T> collection, IEnumerable<T> items) {

    if (collection is List<T> list) {

        list.AddRange(items);

    }
    else {

        foreach (T item in items)
            collection.Add(item);

    }

}

public static void Insert<T>(this ICollection<T> collection, int index, T item) {

    if (index < 0 || index > collection.Count)
        throw new ArgumentOutOfRangeException(nameof(index), "Index was out of range. Must be non-negative and less than the size of the collection.");

    if (collection is IList<T> list) {

        list.Insert(index, item);

    }
    else {

        List<T> temp = new List<T>(collection);

        collection.Clear();

        collection.AddRange(temp.Take(index));
        collection.Add(item);
        collection.AddRange(temp.Skip(index));

    }

}