Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding Items to List<int> By Index Dynamically without using .Add()

Tags:

c#

list

I was trying to add items to list without using .Add() dynamically , Please notice I cant use alternative data structures like dictionary or simple array or even a HashSet due to the nature of my project. I need a workout solution to solve the below problem as it is :

List<int> initA = new List<int>();
for (int i = 0; i < m; i++)
     initA[i] = i;

UPDATE : However if anyone suggests me a better datastructure to implement the following idea then I can use it as alternative :

I have set such that A for example :

A[0] = (1,2,3,4,5...)
A[1] = (10,20,30,40 ...)

and I need direct access such that : A[0][1]=2 , A[1][3]=40 I don't know what is the size of the inner array (the actual size of set elements) thats why I implement this set as Array of Lists and I cant use Jagged Array for the inner array since I don't know its size. the set elements are added at the runtime.

Any Suggestions for solving the first Issue ? or even a suggestion to replace the strategy of represent such set ?

Please notice that I need effecient data strcture since A will store >1M sets.

This is very easy task in C++ where you can use pointers ... in fact this my work around for the problem since its risky to use unsafe code in C#

like image 915
Hassan8541 Avatar asked Feb 11 '26 14:02

Hassan8541


2 Answers

You can work around with Dictionary:

Usage:

Vector<string> v = new Vector<string>();
v[0] = "item0";
v[10] = "item10";
string s = v[10]; //s will be "item10"

Code:

class Vector<T>
    {
        Dictionary<int,T> list;

        public Vector ()
        {
           this.list = new Dictionary<int,T>();
        }

        public T this [int index]{
            get
            {
                if (list.ContainsKey(index))
                    return list[index];
                else return default(T);
            }
            set {
                if (list.ContainsKey(index))
                    list[index] = value;
                else 
                    list.Add(index,value);
            }

        } 
    }
like image 75
eakgul Avatar answered Feb 14 '26 04:02

eakgul


You can't.

A list data structure only allows you to add items with the Add method (or similar methods, e.g. AddRange). The indexer can only be used to modify an entry at a specific position. It cannot be used to add entries to an initially empty list.

So, you definitely need to fill your list before you can modify an item at a specific position, e.g.:

List<int> initA = new List<int>(new int[m]);
for (int i = 0; i < m; i++)
     initA[i] = i;

Note that the first line is equivalent to adding m zeroes in a loop, so, technically, you did not avoid "adding" items.

like image 42
Heinzi Avatar answered Feb 14 '26 04:02

Heinzi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!