Intro.
A query variable is always an enumerable type that will produce a sequence of elements when it is iterated over in a foreach statement or a direct call to its IEnumerator.MoveNext method.
Syntax
from .. in ..
[ join .. in .. on .. equals .. ]
[ where | orderby .. ascending | descending | let ]
[ group .. by .. into .. ]
select new {}
Group clause
var queryCountryGroups =
from country in countries
group country by country.Name[0];
Select clause
var queryNameAndPop =
from country in countries
select new { Name = country.Name, Pop = country.Population };
Orderby clause
IEnumerable<Country> querySortedCountries =
from country in countries
orderby country.Area, country.Population descending
select country;
Join clause
var categoryQuery =
from cat in categories
join prod in products on cat equals prod.Category
select new { Category = cat, Name = prod.Name };
Let clause
string[] names = { "Svetlana Omelchenko", "Claire O'Donnell", "Sven Mortensen", "Cesar Garcia" };
IEnumerable<string> queryFirstNames =
from name in names
let firstName = name.Split(' ')[0]
select firstName;
foreach (string s in queryFirstNames)
Console.Write(s + " ");
//Output: Svetlana Claire Sven Cesar
Subqueries in a query expression
var queryGroupMax =
from student in students
group student by student.GradeLevel into studentGroup
select new
{
Level = studentGroup.Key,
HighestScore =
(from student2 in studentGroup
select student2.Scores.Average())
.Max()
};
// percentileQuery is an IEnumerable<IGrouping<int, Country>>
var percentileQuery =
from country in countries
let percentile = (int) country.Population / 10_000_000
group country by percentile into countryGroup
where countryGroup.Key >= 20
orderby countryGroup.Key
select countryGroup;
// grouping is an IGrouping<int, Country>
foreach (var grouping in percentileQuery)
{
Console.WriteLine(grouping.Key);
foreach (var country in grouping)
Console.WriteLine(country.Name + ":" + country.Population);
}
Standard query operators
Ref: https://docs.microsoft.com/en-us/dotnet/api/system.linq.enumerable.selectmany?view=netcore-3.1
Where Select SelectMany Skip SkipWhile
Take TakeWhile Join GroupJoin Concate
OrderBy OrderByDescending ThenBy ThenByDescending Reverse
GroupBy Distinct Union Intersect Except
AsEnumerable AsQueryable ToArray ToList ToDictionary
ToLookup OfType Cast SequenceEqual First
FirstOrDefault Last LastOrDefault Single SingleOfDefault
ElementAt ElementAtOrDefault DefaultEmpty All Any
Contains Count LongCout Sum Min
Max Average Aggregate equal/Equals from/From
in/In into/Into key let Group
Range Repeat
Top comments (0)