Subscribe to CurtisRutland.Write("...");        RSS Feed
-----

New Extension Method for IList<T>: SafeInsert<T>

Icon Leave Comment
IList.Insert takes an index and a value, and attempts to insert that value at that index, pushing all following values out to the next index. Of course, that index must exist to do the insert. If it doesn't, an exception is thrown.

I figured, why? If I want to move something to position 50, but there are only 5 values in the List, is it reasonable to assume that I want it to go to the last spot, since 50 isn't available? Maybe. Especially in the case where I'm presenting the user a grid, and allowing them to change a row's index manually. I'd rather not bother testing the number they enter, and just assume that if they put an index greater than exists that they want it to be inserted at the end.

This really isn't challenging code or anything, but it's useful, and the first time I thought of it, so I'll share:

public static int SafeInsert<T>(this IList<T> list, int index, T val) {
    int newIndex;
    if (index < 0)
        newIndex = 0;
    else if (index > list.Count)
        newIndex = list.Count;
    else
        newIndex = index;
    list.Insert(newIndex, val);
    return newIndex;
}



Edit: Updated to be a bit smarter. I figured it might be useful to know exactly where the value ends up being inserted, so it returns the inserted index now.

0 Comments On This Entry

 

Trackbacks for this entry [ Trackback URL ]

There are no Trackbacks for this entry

Recent Entries

Recent Comments

2 user(s) viewing

2 Guests
0 member(s)
0 anonymous member(s)