Saturday, September 12, 2009

3 ways to loop into LINQ query output

This article shows us how to iterate into LINQ query output.
to know how let's see this example.

first let's say that we have this class


//Customer class
public class Customer
{
private int _id;
public int Id
{
get { return _id; }
set { _id = value; }
}

private string _name;
public string Name
{
get { return _name; }
set { _name = value; }
}

private string _city;
public string City
{
get { return _city; }
set { _city = value; }
}
}

//then we use object initialization to initialize a list of "Customer"
List<Customer> listofCustomers = new List
<Customer
>{
new Customer{ Id = 1, Name = "ahmed", City = "Cairo" },
new Customer{ Id = 2, Name = "mohamed", City = "Alex" },
new Customer{ Id = 3, Name = "Sameh", City = "Luxor" } };

//now we need to create our LINQ query
var query = listofCustomers
.Where(city => city.City.ToLower() == "alex".ToLower() && city.City.ToLower() == "cairo".ToLower())
.Select(s => new { s.Id, s.Name, s.City }).OrderBy(c => c.City);


now if we need to get data from our query we have many ways here will see 3 ways

1- First way (for loop):
------------------------
int x = query.Count();
for (int z = 0; z < x; z++) { Response.Write(string.Format( "ID = {0}, Name = {1}, City Name ={2}",
query.ElementAt(z).Id, query.ElementAt(z).Name, query.ElementAt(z).City));
}


2-Second way (List.ForEach):
--------------------------------
query.ToList().ForEach(obj => Response.Write(string.Format("ID = {0}, Name = {1}, City Name ={2}", obj.Id, obj.Name, obj.City)));


3- Third way (foreach):
-----------------------------
foreach (var obj in query)
{
Response.Write(string.Format("ID = {0}, Name = {1}, City Name ={2} ", obj.Id,
obj.Name, obj.City));
}