The
following code creates a generic list based on a custom class and
then performs a LINQ query:
following code creates a generic list based on a custom class and
then performs a LINQ query:
//Declare List Object
public static List<GPRider> riderList;
//Declare Class Object
public class GPRider
{
public int Number { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Team { get; set; }
public string BikeMake { get; set; }
public string BikeModel { get; set; }
}
//Create Data To Be Used
public static void createRiders()
{
riderList = new List<GPRider>{
new GPRider {Number=46, FirstName=“Valentino”, LastName=“Rossi”,
Team=“Factory Yamaha”, BikeMake=“Yamaha”, BikeModel=“M1”},
new GPRider {Number=99, FirstName=“Jorge”, LastName=“Lorenzo”,
Team=“Factory Yamaha”, BikeMake=“Yamaha”, BikeModel=“M1”},
new GPRider {Number=69, FirstName=“Nicky”, LastName=“Hayden”,
Team=“Factory Ducati”, BikeMake=“Ducati”, BikeModel=“DesmoGP13”},
new GPRider {Number=35, FirstName =“Cal”, LastName=“Crutchlow”,
Team=“Tech 3”, BikeMake=“Yamaha”, BikeModel=“M1”}
};
}
//Finally, LINQ Query Example For Generic List
public static void RiderQuery()
{
//populate the Generic List
createRiders();
//create the LINQ query
var linqQuery =
from r in riderList
select new { r.FirstName, r.LastName, r.Number, r.Team,
r.BikeMake, r.BikeModel };
//Loop through LINQ query results
foreach (var rider in linqQuery)
{
Console.WriteLine(“{0} {1}, #{2}, rides a {3} {4}, for the {5} team.”,
rider.FirstName, rider.LastName, rider.Number, rider.BikeMake,
rider.BikeModel, rider.Team);
}
Console.ReadLine();
}