class Program
{
static void Main(string[] args)
{
List<Car> ListOfCar = new List<Car>()
{
new Car {name = "Toyota" , owner = "Alex" , model = 1992},
new Car {name = "Mitsubishi", owner = "Jeff" , model = 2005},
new Car {name = "Land Rover", owner = "Danny", model = 2001},
new Car {name = "BMW" , owner = "Danny", model = 2006},
new Car {name = "Subaru" , owner = "Smith", model = 2003}
};
///BASIC LINQ SINTAX
///
IEnumerable<Car> QueryResult = from car in ListOfCar
select car;
foreach (Car car in QueryResult)
Console.WriteLine(car.name);
///PROJECTION
///based on an existing object type
IEnumerable<CarOwner> QueryResult = from car
in ListOfCar
select new CarOwner { owner_name = car.owner };
foreach (CarOwner owner in QueryResult)
Console.WriteLine(owner.owner_name);
///Projections using Anonymous Types
///type of the variable is unknown until. it�s assigned for the first time.
///
var QueryResult = from car in ListOfCar
select new
{
car_name = car.name,
owner_name = car.owner
};
Console.WriteLine("PROJECTION ANONYMOUS TYPE");
foreach (var entry in QueryResult)
Console.WriteLine(entry.car_name);
///REFINING DATA
///select by conditions
///
IEnumerable<Car> QueryResult = from car in ListOfCar
where car.name == "Subaru"
select car;
foreach (Car car in QueryResult)
Console.WriteLine(car.name);
///ORDER BY
///
IEnumerable<Car> QueryResult = from car in ListOfCar
orderby car.model descending
select car;
foreach (Car car in QueryResult)
Console.WriteLine(car.model + "," + car.name);
///GROUPING
///
var QueryResult = from car in ListOfCar
group car by car.owner into carOnwerGroup
select carOnwerGroup.Key;
///JOINS
///join LINQ
///
List<Car> ListOfCars = new List<Car>()
{
new Car {name = "Mitsubishi", owner = "Jeff" , model = 2005},
new Car {name = "Land Rover", owner = "Danny", model = 2001},
new Car {name = "Subaru" , owner = "Smith", model = 2003},
new Car {name = "Toyota" , owner = "Alex" , model = 1992},
new Car {name = "BMW" , owner = "Danny", model = 2006},
};
List<CarOwner> ListOfCarOwners = new List<CarOwner>()
{
new CarOwner {owner_name = "Danny", age = 22},
new CarOwner {owner_name = "Jeff" , age = 35},
new CarOwner {owner_name = "Smith", age = 19},
new CarOwner {owner_name = "Alex" , age = 40}
};
var QueryResult = from car in ListOfCars
join carowner in ListOfCarOwners on car.name equals carowner.owner_name
select new
{
name = car.name,
owner = car.owner,
owner_age = carowner.age
};
foreach (var entry in QueryResult)
Console.Write(entry.name + "," + entry.owner + "," + entry.owner_age);
Console.Read();
}
}
class Car
{
public string name { get; set; }
public string owner { get; set; }
public int model { get; set; }
}
class CarOwner
{
public string owner_name { get; set; }
public int age { get; set; }
}
full article
http://net.tutsplus.com/tutorials/asp-net/net-linq-from-scratch/
0 komentar:
Posting Komentar