Reputation: 1
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
Reputation: 11
its simple
foreach (var c in customers)
{
Console.WriteLine(c.FirstName );
Console.WriteLine(c.LastName );
Console.WriteLine(c.DateOfBirth );
}
Upvotes: 0
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
Reputation: 3380
You can do this via c
foreach variable.
foreach (var c in customers)
{
Console.WriteLine(c.FirstName);
}
Upvotes: 0
Reputation: 1460
In your foreach, you're writing out the wrong variable:
foreach (var c in customers)
{
Console.WriteLine(c.FirstName);
}
Upvotes: 0
Reputation: 2520
It should be something like:
foreach (var c in customers)
{
Console.WriteLine(c.FirstName);
Console.WriteLine(c.LastName);
}
Upvotes: 0