0

I created the list

List<Worker> list = new List<Worker>();

In the class "Worker" are 2 variables:

public static int ID = 0;
public string Name;

When i create the list, i want to output only the name of each worker, so i created a for-loop

for (int i = 0; i < temp.Length; i++)
        {
            Console.WriteLine($"Worker {i+1}: {//name of worker}");
        }

but i don`t know how to extract the variable "Name" from the list

Panagiotis Kanavos
  • 120,703
  • 13
  • 188
  • 236

2 Answers2

3

Well as the Worker has a Name property, then you can access it as simple as this:

for (int i = 0; i < temp.Length; i++)
{
     Console.WriteLine($"Worker {i+1}: {temp[i].Name}");
}
Ashkan Mobayen Khiabani
  • 33,575
  • 33
  • 102
  • 171
0

When querying (in your case you want index and Name) try using Linq which has been designed for querying:

  // When querying you can easily add conditions - Where, order - OrderBy etc.
  var query = list 
    .Select((worker, i) => $"Worker {i + 1}: {worker.Name}");

Then you can easily print it out:

 foreach (item in query)
     Console.WriteLine(item);   

Or even

 Console.WriteLine(string.Join(Environment.NewLine, query));    
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215