如何在ICollection中将项添加到特定索引中?

时间:2013-12-18 07:39:20

标签: .net wpf list c#-4.0 collections

代码:

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>

如何在ICollection中将项添加到特定索引中?

2 个答案:

答案 0 :(得分:4)

ICollection<T> does not have insert method允许在指定的索引位置插入。

相反,您可以使用具有插入方法的IList<T>

void Insert(int index, T item);

您可以这样使用:

controls.TestItems.Add(4, IC);

答案 1 :(得分:0)

如果可以避免的话,我不建议这样做,但这里是 InsertICollection 扩展方法的可能实现:

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));

    }

}

在调用 ClearAdd 时,请注意潜在的副作用。这也是非常低效的,因为它需要清除 ICollection 并重新添加所有项目,但有时绝望的时候需要采取绝望的措施。