Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

What is the difference between list[i] vs list.ToList()[i] in C#?

I am coming back to C# after a long time. Usually, when I want to get or set some value at a specific index, I use .list[i] but recently I have noticed .list.ToList()[i] pattern.

Question:

What is the difference OR advantage of that?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Code:

var randomWords = new List<string>{ "abc", "def", "ghi"};

for (int i = 0; i < randomWords.Count; i++)
{
  Console.WriteLine(randomWords[i]); 
  Console.WriteLine(randomWords.ToList()[i]);
}

Output:

abc
abc
def
def
ghi
ghi

>Solution :

ToList() is a Linq extension method that will create a List<T> from any IEnumerable<T>, such as arrays, lists, or even a query that needs to be executed.

If you call it on something that’s already a List<T>, it will create a copy of that list and get the ith element, which is not functionally different other than you’re working with a shallow copy of the list.

Without knowing what .list is it’s hard to know why someone would do that – perhaps .list is a poorly named property of a type that does not have an indexed, or a lazy-loaded query?

If .list is already a list or has an indexer, I see no benefit of creating another list just to call the indexer.

Even if .list did not have an indexer, there are more efficient ways to get the ith element without creating a list.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading