0

I got this sample List<>

List<string> pizzas = new List<string>();
pizzas.Add("Angus Steakhouse");
pizzas.Add("Belly Buster");
pizzas.Add("Pizza Bianca");
pizzas.Add("Classic Cheese");
pizzas.Add("Friday Special");

I just want to know how to return the string using an index?

Like for sample, I will input "1" and it will return "Belly Buster"

Thanks guys!

Ryan
  • 1,783
  • 8
  • 27
  • 42

5 Answers5

3

You should be able to use:

pizzas[1]
David Z.
  • 5,621
  • 2
  • 20
  • 13
3
var str = pizzas[1]; //Tada!!!!
Josh
  • 44,706
  • 7
  • 102
  • 124
1

If you just want to access the particular element and get back the string, you can do this:

List<string> pizzas = new List<string>();
pizzas.Add("Angus Steakhouse");
pizzas.Add("Belly Buster");
pizzas.Add("Pizza Bianca");
pizzas.Add("Classic Cheese");
pizzas.Add("Friday Special");

string result = pizzas[1]; // result is equal to "Belly Buster"

If you want to actually input the data and get the result back, in say a console application, you can do this:

Console.Write("Index: ");
int index = Int32.Parse(Console.ReadLine());

Console.WriteLine("You selected {0}.", pizzas[index]);

The reason this behaves this way is because List(T) implements what is called an indexer. It's a special property which lets you access the object with an array-like syntax. Most generic collections in the .NET BCL have indexers.

Michael J. Gray
  • 9,784
  • 6
  • 38
  • 67
1

Since you list is of type string so you can assign it directly to string type variable like this.

string str = pizzas[1]; // str = Belly Buster

Adil
  • 146,340
  • 25
  • 209
  • 204
0

You can also do this, but it looks like the previous posts are right as well.

for(int i = 0; i < pizzas.Count; i++)
    Console.WriteLine(pizzas.ElementAt(i));
Console.ReadLine();

Edit 1:

If it's not obvious, the specific index that you wanted (1), would be accessed like so:

string pizza = pizzas.ElementAt(1);

Edit 2:

Faulty code. See edit 3.

Edit 3:

Given the two methods, let's test them.

Code:

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;

namespace ElementAtOrIndex
{
    class Program
    {
        // Declare/initialize static variables.
        static Stopwatch timer = new Stopwatch();
        static List<long> ElementAtTimes = new List<long>();
        static List<long> IndexTimes = new List<long>();

        static void Main(string[] args)
        {
            // Declare/initialize variables.
            int count = 100000;
            int iterations = 1000;

            // Just initializes a list with elements from 0 to count.
            // Slower than for loops, but pithy for an example on SO.
            List<int> list = Enumerable.Range(0, count).ToList<int>();

            // Assert that both methods are equal.
            for (int i = 0; i < list.Count; i++)
            {
                if (list.ElementAt(i) != list[i])
                {
                    Console.WriteLine("Both methods are not equal!");
                    Environment.Exit(1);
                }
            }
            Console.WriteLine("Both methods are equal!");

            // Time ElementAt access *iterations* times by copying into a variable.
            for (int i = 0; i < iterations; i++)
            {
                // [Re]start the timer.
                timer.Reset();
                timer.Start();

                int temp;
                for (int j = 0; j < list.Count; j++)
                    temp = list.ElementAt(j);

                // Note the time. 
                ElementAtTimes.Add(timer.ElapsedTicks);
            }

            // Time Index access *iterations* times by copying into a variable.
            for (int i = 0; i < iterations; i++)
            {
                // [Re]start the timer.
                timer.Reset();
                timer.Start();

                int temp;
                for (int j = 0; j < list.Count; j++)
                    temp = list[j];

                // Note the time. 
                IndexTimes.Add(timer.ElapsedTicks);
            }

            // Output times.
            Console.WriteLine("Average time for ElementAt access: {0} ns", ElementAtTimes.Average() / count * 100);
            Console.WriteLine("Average time for Index access: {0} ns", IndexTimes.Average() / count * 100);

            Console.ReadLine();
        }
    }
}

Test:

http://goo.gl/Tf10R

Output:

Both methods are equal!
Average time for ElementAt access: 25.101014 ns
Average time for Index access: 12.961065 ns

Comments:

When it comes to errors, the MSDN documentation and a wealth of empirical evidence suggests that such concerns are wholly unfounded. If the list changes, then of course those changes will be reflected by both access methods.

The index access method is definitely* faster, but I want to downplay how much. This is timing 100,000 accesses. Access by access, it's only a few nanoseconds faster. That will eventually add up, but is unnecessary optimization for most applications and both methods literally end up doing the same thing.

Also, while this is only showing the timing of accesses to a List of type int, I have tested Lists of type double, float and string with similar results. I can post those versions if requested.

*The index access method should be faster in all cases, but mileage varies widely on hardware. My computer's access times for the ElementAt() and index access methods are 5.71ns and .27ns, respectively.

lordcheeto
  • 1,092
  • 12
  • 16