Earth
Earth

Reputation: 3571

How to add an item into a particular index in ICollection?

Code:

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>

How to add an item into a particular index in ICollection?

Upvotes: 2

Views: 4822

Answers (2)

Rohit Vats
Rohit Vats

Reputation: 81243

ICollection<T> does not have insert method which allows to insert at specified index position.

Instead you can use IList<T> which does have insert method:

void Insert(int index, T item);

You can use like this:

controls.TestItems.Insert(4, IC);

Upvotes: 6

gsemac
gsemac

Reputation: 852

I wouldn't recommend doing this if you can avoid it, but here's a possible implementation for an Insert extension method for 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));

    }

}

Just be wary of potential side effects when calling Clear and Add. This is also horribly inefficient because it requires clearing the ICollection and re-adding all of the items, but sometimes desperate times call for desperate measures.

Upvotes: 0

Related Questions