hello world
hello world

Reputation: 807

Resizing List<T>

I want to resize my List<T>. ie. change the count of the List with respect to some conditions. Right now, Iam doing it using an Array like so :-

private MyModel[] viewPages = GetPagesFromAPI().ToArray();

if (viewPages.Count % 6 == 0) 
{
   Array.Resize(ref newViewPages, viewPages.Length / 6);
} 
else
{
   Array.Resize(ref newViewPages, viewPages.Length / 6 + 1);
}

But, I believe this is not a proper way to do it, since this would be heavy on my application and may cause memory issues. Is there a way I can do it using something likeList<MyModel> viewPageList?

Any help is appreciated.

Upvotes: 0

Views: 6540

Answers (1)

Yuval Itzchakov
Yuval Itzchakov

Reputation: 149548

I want to resize my List<T>

You have misunderstood the purpose of a List<T>. By definition, a list is an auto re-sizing collection, there is no need to manually resize it. As you add elements, it will check it's internal array backing storage and increase it's size when it needs to (the current implementation detail will double it's backing store).

This is how List<T>.Add is implemented:

// Adds the given object to the end of this list. The size of the list is
// increased by one. If required, the capacity of the list is doubled
// before adding the new element.
public void Add(T item)
{
     if (_size == _items.Length) EnsureCapacity(_size + 1);
     _items[_size++] = item;
    _version++;
}

EnsureCapacity will make sure the backing array has sufficient storage.

Upvotes: 0

Related Questions