Object filtering using LINQ

LINQ:
Query is an integrated feature of programming language(like C# and VB.NET).LINQ(Language Integrated query), a set of language extension that allows you to perform queries without leaving the comfort of programming language. It has set of keyword to build a query expression.These query expression can select,filter,sort,group and transform data.


LINQ to Objects:
It is Simplest form of LINQ, allow you to query collection of memory objects. It replace the iteration logic(such as foreach block) with declarative LINQ expression.LINQ using the new set of keywords, including from,in,where and select.


public class Car
{

public Car(string m_Make,string m_Color,int m_Price)
{
Make = m_Make;
Color = m_Color;
Price = m_Price;
}

public string Make { get; set; }
public string Color { get; set; }
public int Price { get; set; }

}



public class LinQApp
{

static void Main(string[] args)
{
ListFiltering();
Console.ReadLine();
}

private static void ListFiltering()
{
List Cars = new List();
Cars.Add(new Car("TATA","Red",100000));
Cars.Add(new Car("TATA", "Yellow", 100000));
Cars.Add(new Car("TATA", "White", 100000));
Cars.Add(new Car("Maruti", "Red", 300000));
Cars.Add(new Car("Maruti", "Yellow", 300000));
//Logic: Show All cars with Red Color
Console.WriteLine("");
//Iterative Method
Console.WriteLine("List Filter Normal Way:");
foreach (Car C in Cars)
{
if (C.Color == "Red")
Console.WriteLine(C.Make + " Price " + C.Price);
}
//LINQ Query Method
Console.WriteLine("");
Console.WriteLine("List Filter LINQ Way:");
IEnumerable MatchCars;


MatchCars = from C in Cars
where C.Color == "Red"
select C; //here C is the object with type of Car

//After the filtering condition all the attributes of car is selected.


foreach (Car MatCar in MatchCars)
{
Console.WriteLine(MatCar.Make + " Price " + MatCar.Price);
}

}

}


Output:

List Filter Normal way:
TATA Price 100000
Maruti Price 300000



List Filter LINQ way:
TATA Price 100000
Maruti Price 300000

No comments: