user3475989
user3475989

Reputation: 1

How to retrieve the content of returned list collection from a static class

How can I get each element (firstname, lastname) of the customer class which is assigned in customers in Main. I am not able to do customers.firstname in main.

public static class CustomerProvider
{
    public static List<Customer> GetRandomCustomers()
    {
        var result = new List<Customer>();
        var customer1 = new Customer();
        customer1.FirstName = "Tony";
        customer1.LastName = "Romo";
        customer1.DateOfBirth = Convert.ToDateTime("03 / 10 / 88");
        result.Add(customer1);

        return result;
    }

    static void Main(string[] args)
    {
        var customers=  CustomerProvider.GetRandomCustomers();

        foreach (var c in customers)
        {
            Console.WriteLine(customers);
        }

        Console.ReadLine();
        Console.ReadLine(); 
    }

Upvotes: 0

Views: 59

Answers (5)

Rama Rao
Rama Rao

Reputation: 11

its simple

foreach (var c in customers)
{
    Console.WriteLine(c.FirstName );
    Console.WriteLine(c.LastName );
    Console.WriteLine(c.DateOfBirth );
}

Upvotes: 0

aw04
aw04

Reputation: 11187

It's important to understand what your foreach is doing.

customers is your collection of the Customer class and c is a single different Customer each time through the loop.

So you will write it like this:

foreach (var c in customers)
{
    Console.WriteLine(c.FirstName);
    Console.WriteLine(c.LastName);
}

Upvotes: 1

Oleksandr Kobylianskyi
Oleksandr Kobylianskyi

Reputation: 3380

You can do this via c foreach variable.

foreach (var c in customers)
{
    Console.WriteLine(c.FirstName);
}

Upvotes: 0

safetyOtter
safetyOtter

Reputation: 1460

In your foreach, you're writing out the wrong variable:

    foreach (var c in customers)
    {
        Console.WriteLine(c.FirstName);
    }

Upvotes: 0

It should be something like:

foreach (var c in customers)
  {
      Console.WriteLine(c.FirstName);
      Console.WriteLine(c.LastName);
  }

Upvotes: 0

Related Questions