# LINQ
what is LINQ ?
Language-Integrated Query or linq is a library provided b .Net to easily work on collections of elements under the system namespace
examples and commonly used linq expressions
· Where - use to filter the collection base on the condition (predicate/function)
var queryGermanShepherds = from dog in dogs
where dog.Breed == DogBreed.GermanShepherd
select dog;
var linqExperts = programmers
.Where(p => p.IsNewToLINQ)
.Select(p => new LINQExpert(p));
· Select - use to transform to a new collection
var queryCats = from dog in dogs
select dog.TurnIntoACat();
var cats1 = dogs.Select(dog => dog.TurnIntoACat());
var cats2 = dogs.Select(dog => new Cat() { name = dog.name });
· OrderBy, OrderByDescending - ease the sorting of the collection base on the condition
class Person {
public string name { get; set; }
public int age { get; set; }
}
var PersonOrderByAge = people.OrderBy(person => p.Age);
· Cast - go through each element on collection and try to change its type to the given destitation type. it throws exception if it fails
List trucks = vehicles.Cast();
· OfType - simillar to Cast but does not throw exception and return only the element that can belong to the given destination type
List helicopter = vehicles.OfType();
· Last, LastOrDefault - returns the element of the last occurence of the given condition. The difference is that Last will throw an exception if it didn't found any, the later returns the default value
· First, FirstOrDefault - returns the element of the first occurence of the given condition. The difference is that First will throw an exception if it didn't found any, the later returns the default value
· Single, SingleOrDefault - returns the element of the given condition. The difference is that Single will throw an exception if it didn't found any, the later returns the default value.
Single vs First - `single` make sure that it will only return 1 occurence of the given condition. it means that it will go through all elements in the collection then returns, while the First return right away upon encountering the condition
var firstPerson = people.FirstOrDefault(person => person.Name.StartsWith("A"));
var lastPerson = people.LastOrDefault(person => person.Name.StartsWith(“Z”));
var singlePerson = people.SingleOrDefault(person => person.Name.StartsWith(""))
· Min, Max, Average, Sum, Count - often used against numeric types and in SQL these are called aggregates
var minAge = people.Age.Min();
var maxAge = people.Age.Max();
var averageAge = people.Age.Average();
var numberOfPeople = people.Count();