Hakan Ali Yasdi
Hakan Ali Yasdi

Reputation: 115

Getting elements of List by index in C#

I am trying to access List items in C#. I have a list as List<int[]>. I have to assign first three elements of List, which are integer arrays, to variables. This is what I do;

int[] c1 = lst.ElementAt(0);
int[] c2 = lst.ElementAt(1);
int[] c3 = lst.ElementAt(2);

I also tried accessing it by lst[0], lst[1], lst[2] instead of ElementAt(). But although first three elements of list are different from each other, all variables take the value of first item of list. I checked values with debugging. What am I doing wrong and also another question in my mind is, what is the difference between lst[0] and lst.ElementAt(0).

Upvotes: 1

Views: 11094

Answers (1)

lerthe61
lerthe61

Reputation: 367

You did something wrong. Because default implementation for ElementAt look like:

 public static TSource ElementAt<TSource>(this IEnumerable<TSource> source, int index) {
        if (source == null) throw Error.ArgumentNull("source");
        IList<TSource> list = source as IList<TSource>;
        if (list != null) return list[index];
        if (index < 0) throw Error.ArgumentOutOfRange("index");
        using (IEnumerator<TSource> e = source.GetEnumerator()) {
            while (true) {
                if (!e.MoveNext()) throw Error.ArgumentOutOfRange("index");
                if (index == 0) return e.Current;
                index--;
            }
        }
    }

For anything that implement IList it will use the same indexer as you do

Upvotes: 4

Related Questions