Adam
Adam

Reputation: 45

Show specify element from ICollection<>

I was interested in how I can get a specific element of the collection. I was looking for documentation on how to do it, but I found nothing about it. I have ICollection and i want show ModelName located in index 3.

Car class

public class Car{
   public string Brand;
   public string Model;
   public string Engine;
   public string Weight;
}

If i create List instead ICollection i want this using:

public List<Car> Cars;
string carModel = Cars[3].Model;

Upvotes: 0

Views: 350

Answers (1)

Gabriel Luci
Gabriel Luci

Reputation: 40908

The interface ICollection<T> does not guarantee any consistent order, which is why it does not include any way to access a specific item in the collection by its position.

The IList<T> interface implements ICollection and is used specifically for lists "that can be individually accessed by index."

So if you are accessing the list as an ICollection<T>, you cannot do it. But if you access it as List<T> or IList<T>, then you can.

var list = new List<string> { "zero", "one", "two" };
Console.WriteLine(list[0]); //works

var ilist = (IList) list;
Console.WriteLine(ilist[0]); //works

var collection = (ICollection) list;
Console.WriteLine(collection[0]); //compiler error

Upvotes: 5

Related Questions