LINQtoObjectsreferstotheuseofLINQquerieswithanyIEnumerablecollection.
Section65.1:UsingLINQtoObjectsinC#
AsimpleSELECTqueryinLinq
staticvoidMain(string[]args)
{
string[]cars={“VWGolf”,
“OpelAstra”,
“AudiA4”,
“FordFocus”,
“SeatLeon”,
“VWPassat”,
“VWPolo”,
“MercedesC-Class”};
varlist=fromcarincars
selectcar;
StringBuildersb=newStringBuilder();
foreach(stringentryinlist)
{
sb.Append(entry+”\n“);
}
Console.WriteLine(sb.ToString()); Console.ReadLine();
}
Intheexampleabove,anarrayofstrings(cars)isusedasacollectionofobjectstobequeriedusingLINQ.InaLINQ query, the from clause comes first in order to introduce the data source (cars) and the range variable (car). When the query is executed, the range variable will serve as a reference to each successive element in cars. Because the compiler can infer the type of car, you do not have to specify it explicitly
Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:
SELECTwithaWHEREClause
varlist=fromcarincars
wherecar.Contains(“VW”)
selectcar;
TheWHEREclauseisusedtoquerythestringarray(cars)tofindandreturnasubsetofarraywhichsatisfiesthe
WHEREclause.
Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:
GeneratinganOrderedList
varlist=fromcarincars
orderbycarascending
selectcar;
Sometimes it is useful to sort the returned data. The orderby clause will cause the elements to be sorted according to the default comparer for the type being sorted.
Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:
Workingwithacustomtype
Inthisexample,atypedlistiscreated,populated,andthenqueried
publicclassCar
{
publicStringName{get;privateset;}
publicintUnitsSold{get;privateset;}
publicCar(stringname,intunitsSold)
{
Name=name;
UnitsSold=unitsSold;
}
}
classProgram
{
staticvoidMain(string[]args)
{
varcar1=newCar(“VWGolf”,270952);
varcar2=newCar(“OpelAstra”,56079);
varcar3=newCar(“AudiA4”,52493);
varcar4=newCar(“FordFocus”,51677);
varcar5=newCar(“SeatLeon”,42125);
var car6 = new Car(“VW Passat”, 97586);
varcar7=newCar(“VWPolo”,69867);
varcar8=newCar(“MercedesC-Class”,67549);
varcars=newList<Car>{
car1,car2,car3,car4,car5,car6,car7,car8}; var list
=fromcarincars
selectcar.Name;
foreach(varentryinlist)
{
Console.WriteLine(entry);
}
Console.ReadLine();
}
}
Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:
Until now the examples don’t seem amazing as one can just iterate through the array to do basically the same. However, with the few examples below you can see how to create more complex queries with LINQ to Objects and achieve more with a lot less of code.
In the example below we can select cars that have been sold over 60000 units and sort them over the number of units sold:
varlist=fromcarincars
wherecar.UnitsSold>60000
orderbycar.UnitsSolddescending
selectcar;
StringBuildersb=newStringBuilder();
foreach(varentryinlist)
{
sb.AppendLine($”{entry.Name}-{entry.UnitsSold}”);
}
Console.WriteLine(sb.ToString());
Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:
In the example below we can select cars that have sold an odd number of units and order them alphabetically over its name:
varlist=fromcarincars
wherecar.UnitsSold%2!=0
orderbycar.Nameascending
selectcar;
Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:
About us and this blog
We are a digital marketing company with a focus on helping our customers achieve great results across several key areas.
Request a free quote
We offer professional SEO services that help websites increase their organic search score drastically in order to compete for the highest rankings even when it comes to highly competitive keywords.
Subscribe to our newsletter!
More from our blog
See all postsRecent Posts
- Chapter97:FileandStreamI/O 27/04/2024
- Chapter96:Delegates 26/04/2024
- Chapter95:Attributes 25/04/2024