【问题标题】:How to add an item into a particular index in ICollection?如何将项目添加到 ICollection 中的特定索引中?
【发布时间】:2014-01-06 06:45:30
【问题描述】:
代码:
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 的特定索引中添加一个项目?
【问题讨论】:
标签:
.net
wpf
list
c#-4.0
collections
【解决方案1】:
ICollection<T> does not have insert method 允许在指定的索引位置插入。
相反,您可以使用IList<T>,它确实具有插入方法:
void Insert(int index, T item);
你可以这样使用:
controls.TestItems.Insert(4, IC);
【解决方案2】:
如果可以避免的话,我不建议这样做,但这里有一个Insert 扩展方法的可能实现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));
}
}
致电Clear 和Add 时请注意潜在的副作用。这也是非常低效的,因为它需要清除 ICollection 并重新添加所有项目,但有时危急时刻需要采取危急措施。