C# Programming Guide Query Expression Basics (C# Programming Guide)
 What is a Query and What Does it Do?
A query is a set of instructions that describes what data to retrieve from a given data source (or sources) and what shape and organization the returned data should have.
A query is distinct from the results that it produces.
Generally, the source data is organized logically as a sequence of elements of the same kind.
A SQL database table contains a sequence of rows.
Similarly, an ADO.NET DataTable contains a sequence of DataRow objects.
In an XML file, there is a "sequence" of XML elements (although these are organized hierarchically in a tree structure).
An in-memory collection contains a sequence of objects.
From an application's viewpoint, the specific type and structure of the original source data is not important.
The application always sees the source data as an IEnumerable<(Of <(T>)>) or IQueryable<(Of <(T>)>) collection.
In LINQ to XML, the source data is made visible as an IEnumerable<XElement>.
In LINQ to DataSet, it is an IEnumerable<DataRow>.
In LINQ to SQL, it is an IEnumerable or IQueryable of whatever custom objects you have defined to represent the data in the SQL table.
Given this source sequence, a query may do one of three things:
-
Retrieve a subset of the elements to produce a new sequence without modifying the individual elements.
The query may then sort or group the returned sequence in various ways, as shown in the following example (assume scores is an int[]):
IEnumerable<> highScoresQuery =
score scores
score > 80
score
score;
-
Retrieve a sequence of elements as in the previous example but transform them to a new type of object.
For example, a query may retrieve only the last names from certain customer records in a data source.
Or it may retrieve the complete record and then use it to construct another in-memory object type or even XML data before generating the final result sequence.
The following example shows a transform from an int to a string.
Note the new type of highScoresQuery.
IEnumerable<string> highScoresQuery2 =
score scores
score > 80
score
String.Format(, score);
-
Retrieve a singleton value about the source data, such as:
-
The number of elements that match a certain condition.
-
The element that has the greatest or least value.
-
The first element that matches a condition, or the sum of particular values in a specified set of elements.
For example, the following query returns the number of scores greater than 80 from the scores integer array:
highScoreCount =
( score scores
score > 80
score)
.Count();
In the previous example, note the use of parentheses around the query expression before the call to the Count method.
You can also express this by using a new variable to store the concrete result.
This technique is more readable because it keeps the variable that store the query separate from the query that stores a result.
IEnumerable<> highScoresQuery3 =
score scores
score > 80
score;
scoreCount = highScoresQuery3.Count();
In the previous example, the query is executed in the call to Count, because Count must iterate over the results in order to determine the number of elements returned by highScoresQuery.
 What is a Query Expression?
A query expression is a query expressed in query syntax.
A query expression is a first-class language construct.
It is just like any other expression and can be used in any context in which a C# expression is valid.
A query expression consists of a set of clauses written in a declarative syntax similar to SQL or XQuery.
Each clause in turn contains one or more C# expressions, and these expressions may themselves be either a query expression or contain a query expression.
A query expression must begin with a from clause and must end with a select or group clause.
Between the first from clause and the last select or group clause, it can contain one or more of these optional clauses: where, orderby, join, let and even additional from clauses.
You can also use the into keyword to enable the result of a join or group clause to serve as the source for additional query clauses in the same query expression.
The Query Variable
In LINQ, a query variable is any variable that stores a query instead of the results of a query. More specifically, 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.
The following code example shows a simple query expression with one data source, one filtering clause, one ordering clause, and no transformation of the source elements.
The select clause ends the query.
Main()
{
[] scores = { 90, 71, 82, 93, 75, 82 };
IEnumerable<> scoreQuery =
score scores
score > 80
score
score;
( testScore scoreQuery)
{
Console.WriteLine(testScore);
}
}
In the previous example, scoreQuery is a query variable, which is sometimes referred to as just a query.
The query variable stores no actual result data, which is produced in the foreach loop.
And when the foreach statement executes, the query results are not returned through the query variable scoreQuery.
Rather, they are returned through the iteration variable testScore.
The scoreQuery variable can be iterated in a second foreach loop.
It will produce the same results as long as neither it nor the data source has been modified.
A query variable may store a query that is expressed in query syntax or method syntax, or a combination of the two.
In the following examples, both queryMajorCities and queryMajorCities2 are query variables:
IEnumerable<City> queryMajorCities =
city cities
city.Population > 100000
city;
IEnumerable<City> queryMajorCities2 = cities.Where(c => c.Population > 100000);
On the other hand, the following two examples show variables that are not query variables even through each is initialized with a query.
They are not query variables because they store results:
highestScore =
( score scores
score)
.Max();
IEnumerable<> scoreQuery =
score scores
score;
highScore = scoreQuery.Max();
IEnumerable<City> largeCityList =
( country countries
city country.Cities
city.Population > 10000
city)
.ToList();
IEnumerable<City> largeCityList2 =
country countries
city country.Cities
city.Population > 10000
city;
List<City> largeCities = largeCityList2.ToList();
Note:
|
|
In the
LINQ documentation, variables that store a query have the word "query" as part of their names.
Variables that store an actual result do not have "query" in their names.
|
For more information about the different ways to express queries, see Query Syntax versus Method Syntax (LINQ).
Explicit and Implicit Typing of Query Variables
This documentation usually provides the explicit type of the query variable in order to show the type relationship between the query variable and the select clause.
However, you can also use the var keyword to instruct the compiler to infer the type of a query variable (or any other local variable) at compile time.
For example, the query example that was shown previously in this topic can also be expressed by using implicit typing:
var queryCities =
city cities
city.Population > 100000
city;
For more information, see Implicitly Typed Local Variables (C# Programming Guide) and Type Relationships in Query Operations (LINQ).
Starting a query expression
A query expression must begin with a from clause.
It specifies a data source together with a range variable.
The range variable represents each successive element in the source sequence as the source sequence is being traversed.
The range variable is strongly typed based on the type of elements in the data source.
In the following example, because countries is an array of Country objects, the range variable is also typed as Country.
Because the range variable is strongly typed, you can use the dot operator to access any available members of the type.
IEnumerable<Country> countryAreaQuery =
country countries
country.Area > 500000
country;
The range variable is in scope until the query is exited either with a semicolon or with a continuation clause.
A query expression may contain multiple from clauses.
Use additional from clauses when each element in the source sequence is itself a collection or contains a collection.
For example, assume that you have a collection of Country objects, each of which contains a collection of City objects named Cities.
To query the City objects in each Country, use two from clauses as shown here:
IEnumerable<City> cityQuery =
country countries
city country.Cities
city.Population > 10000
city;
For more information, see from clause (C# Reference).
Ending a Query Expression
A query expression must end with either a select clause or a group clause.
group Clause
Use the group clause to produce a sequence of groups organized by a key that you specify.
The key can be any data type.
For example, the following query creates a sequence of groups that contains one or more Country objects and whose key is a string value.
var queryCountryGroups =
country countries
country country.Name[0];
For more information about grouping, see group clause (C# Reference).
select Clause
Use the select clause to produce all other types of sequences.
A simple select clause just produces a sequence of the same type of objects as the objects that are contained in the data source.
In this example, the data source contains Country objects.
The orderby clause just sorts the elements into a new order and the select clause produces a sequence of the reordered Country objects.
IEnumerable<Country> sortedQuery =
country countries
country.Area
country;
The select clause can be used to transform source data into sequences of new types.
This transformation is also named a projection.
In the following example, the select clause projects a sequence of anonymous types which contains only a subset of the fields in the original element.
Note that the new objects are initialized by using an object initializer.
var queryNameAndPop =
country countries
{ Name = country.Name, Pop = country.Population };
For more information about all the ways that a select clause can be used to transform source data, see select clause (C# Reference).
Continuations with "into"
You can use the into keyword in a select or group clause to create a temporary identifier that stores a query.
Do this when you must perform additional query operations on a query after a grouping or select operation.
In the following example countries are grouped according to population in ranges of 10 million.
After these groups are created, additional clauses filter out some groups, and then to sort the groups in ascending order.
To perform those additional operations, the continuation represented by countryGroup is required.
var percentileQuery =
country countries
percentile = () country.Population / 10000000
country percentile countryGroup
countryGroup.Key >= 20
countryGroup.Key
countryGroup;
(var grouping percentileQuery)
{
Console.WriteLine(grouping.Key);
(var country grouping)
Console.WriteLine(country.Name + + country.Population);
}
For more information, see into (C# Reference).
Filtering, Ordering, and Joining
Between the starting from clause, and the ending select or group clause, all other clauses (where, join, orderby, from, let) are optional.
Any of the optional clauses may be used zero times or multiple times in a query body.
where Clause
Use the where clause to filter out elements from the source data based on one or more predicate expressions.
The where clause in the following example has two predicates.
IEnumerable<City> queryCityPop =
city cities
city.Population < 200000 && city.Population > 100000
city;
For more information, see where clause (C# Reference).
orderby Clause
Use the orderby clause to sort the results in either ascending or descending order.
You can also specify secondary sort orders.
The following example performs a primary sort on the country objects by using the Area property.
It then performs a secondary sort by using the Population property.
IEnumerable<Country> querySortedCountries =
country countries
country.Area > 500000, country.Population
country;
The ascending keyword is optional; it is the default sort order if no order is specified.
For more information, see orderby clause (C# Reference).
join Clause
Use the join clause to associate and/or combine elements from one data source with elements from another data source based on an equality comparison between specified keys in each element.
In LINQ, join operations are performed on sequences of objects whose elements are different types.
After you have joined two sequences, you must use a select or group statement to specify which element to store in the output sequence.
You can also use an anonymous type to combine properties from each set of associated elements into a new type for the output sequence.
The following example associates prod objects whose Category property matches one of the categories in the categories string array.
Products whose Category does not match any string in categories are filtered out.
The select statement projects a new type whose properties are taken from both cat and prod.
var categoryQuery =
cat categories
prod products cat prod.Category
{ Category = cat, Name = prod.Name };
You can also perform a group join by storing the results of the join operation into a temporary variable by using the into keyword.
For more information, see join clause (C# Reference).
let Clause
Use the let clause to store the result of an expression such as a method call in a new range variable.
In the following example, the range variable s stores the first element of the string array returned by Split.
string[] names = { , , , };
IEnumerable<string> queryFirstNames =
name names
firstName = name.Split( [] { ' ' })[0]
firstName;
(string s queryFirstNames)
Console.Write(s + );
For more information, see let clause (C# Reference).
Subqueries in a Query Expression
A query clause may itself contain a query expression, which is sometimes referred to as a subquery.
Each subquery starts with its own from clause that does not necessarily point to the same data source in the first from clause.
For example, the following query shows a query expression that is used in the select statement to retrieve the results of a grouping operation.
var queryGroupMax =
student students
student student.GradeLevel studentGroup
{
Level = studentGroup.Key,
HighestScore =
( student2 studentGroup
student2.Scores.Average())
.Max()
};
For more information, see How to: Perform a Subquery on a Grouping Operation (C# Programming Guide).
 See Also
Concepts
Reference
Other Resources
|
Guia de Programação C# Noções básicas de expressão de consulta (Guia de programação C#)
 O que é uma consulta e o que É ele?
Uma query é um conjunto de instruções que descrevem qual dado receber de um data source(ou sources) e em qual formato e organização os dados deveriam ter.
Uma query é diferenciada a partir dos resultados que ela produz.
Geralmente, os dados de origem são organizados logicamente como uma sequência de elementos do mesmo tipo.
Uma tabela de um banco de dados SQL contém uma sequência de linhas.
Similarly, an ADO.NET DataTable contains a sequence of DataRow objects.
Em um arquivo XML, existe uma "sequência" de elementos XML (apesar destes serem organizados hierarquicamente em uma estrutura de árvore).
Uma coleçao na mémoria contém uma sequência de objetos.
Do ponto de vista do aplicativo, o tipo específico e a estrutura dos dados de origem original não é importante.
O aplicativo sempre vê os dados de origem como um IEnumerable<(Of <(T>)>) ou IQueryable<(Of <(T>)>) coleção.
Em LINQ to XML, os dados de origem são tornados Visível como um IEnumerable<XElement >.
Em LINQ to DataSet, é um IEnumerable<DataRow >.
Em LINQ to SQL, é um IEnumerable ou IQueryable de qualquer Personalizar objetos que você definiu para representar os dados na tabela SQL.
Dada essa seqüência de origem, uma consulta pode siga um destes três coisas:
-
Recupere um subconjunto dos elementos para produzir uma Novo seqüência sem modificar os elementos individuais.
A consulta pode em seguida, classificar ou agrupar a seqüência retornada em várias formas, conforme o exemplo seguinte (presuma scores é uma int[]):
IEnumerable<> highScoresQuery =
score scores
score > 80
score
score;
-
Recuperar uma seqüência de elementos como no exemplo anterior, mas Transformará-los para um novo tipo de objeto.
Por exemplo, uma consulta pode recuperar apenas os últimos nomes de determinados registros de cliente em uma Origem de dados.
Ou ele pode recuperar o registro completo e usá-lo para criar outro tipo de objeto de memória ou até mesmo dados XML antes de gerar a seqüência do resultado final.
O exemplo a seguir mostra uma Transformarar de um int para um string.
Anotação o novo tipo de highScoresQuery.
IEnumerable<string> highScoresQuery2 =
score scores
score > 80
score
String.Format(, score);
-
Recuperar um valor singleton sobre os dados de origem, tais como:
-
O número de elementos que coincidam com uma determinada condição.
-
O elemento que possui o valor maior ou menor.
-
O primeiro elemento que corresponde a uma condição ou soma de valores específicos de um conjunto especificado de elementos.
Por exemplo, a seguinte consulta retorna o número de pontuação maior do que 80 da matriz de inteiro scores:
highScoreCount =
( score scores
score > 80
score)
.Count();
No exemplo anterior, Anotação o uso de parênteses em torno da expressão de consulta antes da chamada ao método Count.
Você também pode expressar isso usando uma Novo variável para armazenar o resultado de concreto.
Essa técnica é mais legível, pois ele mantém a variável que armazede a consulta separade da consulta que armazede um resultade.
IEnumerable<> highScoresQuery3 =
score scores
score > 80
score;
scoreCount = highScoresQuery3.Count();
No exemplo anterior, a consulta é executada na chamada para Count, porque Count deve iterar sobre os resultados em Ordem para determinar o número de elementos retornados pela highScoresQuery.
 O que é uma expressão de consulta?
Um de expressão de consulta é uma consulta expressa na sintaxe de consulta.
Uma expressão de consulta é uma Primeiro classe Idioma construir.
Ele é como qualquer outra expressão e pode ser usado em qualquer contexto em que uma expressão de C# é válida.
Uma expressão de consulta consiste em um conjunto das cláusulas escrito em uma sintaxe declarativa semelhante a SQL ou XQuery.
Cada cláusula por sua vez contém um ou mais expressões do C# e essas expressões podem se ser uma expressão de consulta ou conter uma expressão de consulta.
Uma expressão de consulta deve começar com um cláusula from e deve terminar com umSelecionar de ou AAgruparar cláusula.
Entre a Primeiro cláusula from e o último select ou group cláusula, ele pode conter um ou mais dessas cláusulas opcionais: onde, orderby, Junção, permitem e até adicionais de cláusulas.
Também pode usar o na palavra-chave para habilitar o resultado de um join ou group cláusula para servir como a Origem para as cláusulas de consulta adicional na mesma expressão de consulta.
A variável de consulta
Em LINQ, uma variável de consulta é qualquer variável que armazena um de consulta em vez do de uma consulta de resultados. Mais especificamente, uma variável de consulta sempre é um tipo enumeráveis que produzirá uma seqüência de elementos quando ele é iterado em uminstrução de foreach ou uma chamada direta para o método IEnumerator.MoveNext.
O exemplo de código a seguir mostra uma expressão de consulta simples com uma fonte de dados, uma cláusula de filtragem, uma cláusula de pedido e nenhuma transformação dos elementos de origem.
A cláusula select termina a consulta.
Main()
{
[] scores = { 90, 71, 82, 93, 75, 82 };
IEnumerable<> scoreQuery =
score scores
score > 80
score
score;
( testScore scoreQuery)
{
Console.WriteLine(testScore);
}
}
No exemplo anterior, scoreQuery é uma variável de consulta de ,que às vezes é chamado de apenas umconsulta.
A variável de consulta armazena não dados resultado real, que são produzidos no loop foreach.
E quando executa a instrução de foreach , os resultados da consulta não são retornados Através a variável de consulta scoreQuery.
Em vez disso, eles são retornados Através a variável de iteração testScore.
A variável scoreQuery pode ser iterada em um segundo loop foreach.
Ela produzirá os mesmos resultados, desde que ele nem a Origem de dados foi modificada.
Uma variável de consulta pode armazenar uma consulta que é expresso na sintaxe de consulta ou sintaxe do método ou uma combinação dos dois.
Os exemplos a seguir, os queryMajorCities e o queryMajorCities2 são variáveis de consulta:
IEnumerable<City> queryMajorCities =
city cities
city.Population > 100000
city;
IEnumerable<City> queryMajorCities2 = cities.Where(c => c.Population > 100000);
Através outro lado, os exemplos de dois a seguir mostram variáveis que não são variáveis de consulta, mesmo em cada é iniciada com uma consulta.
Eles não são variáveis de consulta porque armazenam os resultados:
highestScore =
( score scores
score)
.Max();
IEnumerable<> scoreQuery =
score scores
score;
highScore = scoreQuery.Max();
IEnumerable<City> largeCityList =
( country countries
city country.Cities
city.Population > 10000
city)
.ToList();
IEnumerable<City> largeCityList2 =
country countries
city country.Cities
city.Population > 10000
city;
List<City> largeCities = largeCityList2.ToList();
Observação:
|
|
Na
Documentação de LINQ, variáveis que armazenam uma consulta têm a palavra "consulta" como parte de seus nomes.
Variáveis que armazenam um resultado real não é necessário "consulta" em seus nomes.
|
Para obter mais informações sobre as diferentes maneiras para expressar consultas, consulte Sintaxe de consulta versus sintaxe do método (LINQ).
Explícito e implícita de digitação de variáveis de consulta
Esta documentação geralmente fornece o tipo explícito da variável de consulta em Ordem para mostrar o tipo de relação entre a variável de consulta e o Selecionar cláusula.
No entanto, também pode usar a palavra-chave var para instruir o compilador a inferir o tipo de uma variável de consulta (ou qualquer outra variável local) em tempo de compilação.
Por exemplo, o exemplo de consulta que foi mostrado anteriormente neste tópico também pode ser expresso por meio de digitação implícita:
var queryCities =
city cities
city.Population > 100000
city;
Para obter mais informações, consulte Digitada implicitamente variáveis Local (C# Guia de programação) e Relações de tipo em operações de Consulta (LINQ).
Iniciar uma expressão de consulta
Uma expressão de consulta deve começar com uma cláusula from.
Ele especifica uma Origem de dados juntamente com uma variável de intervalo.
A variável de intervalo representa cada elemento sucessivo na seqüência de origem como a seqüência de origem está sendo envolvida.
A variável de intervalo é digitada altamente com base no tipo de elementos na Origem de dados.
No exemplo a seguir, como countries é uma matriz de objetos de Country , a variável de intervalo também é digitada como Country.
Porque a variável de intervalo é digitada altamente, você pode usar o operador ponto para acessar os membros do tipo disponíveis.
IEnumerable<Country> countryAreaQuery =
country countries
country.Area > 500000
country;
A variável de intervalo está no escopo até que a consulta é finalizada com um ponto-e-vírgula ou com uma cláusula de continuação.
Uma expressão de consulta pode conter Múltiplo cláusulas from.
Use as cláusulas adicionais from quando cada elemento da seqüência de origem é uma coleção ou contém uma coleção.
Por exemplo, suponha que você tiver um conjunto de objetos de Country , cada uma delas conterá uma coleção de objetos City chamado Cities.
Para consultar objetos da cada CityCountry, use duas cláusulas from como mostrado aqui:
IEnumerable<City> cityQuery =
country countries
city country.Cities
city.Population > 10000
city;
For more information, see de cláusula (Referência C#).
Encerrar uma expressão de consulta
Uma expressão de consulta deve terminar com uma cláusula select ou uma cláusula group.
Cláusula de AAgruparar
Use a cláusula group para produzir uma seqüência de grupos organizados por uma chave que você especificar.
A chave pode ser qualquer tipo de dados.
Por exemplo, a consulta a seguir cria uma Cadeia de Caracteres de grupos que contém um ou mais objetos Country e cuja chave é um valor de Cadeia de Caracteres.
var queryCountryGroups =
country countries
country country.Name[0];
Para obter mais informações sobre agrupamento, consulte cláusula de AAgruparar (Referência C#).
Selecionar cláusula
Use a cláusula select para produzir a Tudo outros tipos de seqüências.
Uma cláusula simples select apenas produz uma seqüência do mesmo tipo de objetos como os objetos contidos na Origem de dados.
No exemplo, a Origem de dados contém objetos Country.
A cláusula orderby apenas classifica os elementos em uma Novo ordem e a cláusula select produz uma seqüência de objetos reordenada Country.
IEnumerable<Country> sortedQuery =
country countries
country.Area
country;
A cláusula select pode ser usada para transformar dados de origem em seqüências de novos tipos.
Essa transformação também é chamada de projeção um .
No exemplo a seguir, o de cláusula de selectprojetos uma seqüência de tipos anônimos que contém apenas um subconjunto de campos o elemento original.
Anotação que os novos objetos são inicializados, usando um inicializador de objeto.
var queryNameAndPop =
country countries
{ Name = country.Name, Pop = country.Population };
Para obter mais informações sobre Tudo as formas que uma cláusula select pode ser usado para transformar dados de origem, consulte Selecionar cláusula (Referência C#).
Continuação com "em"
Você pode utilizar a palavra-chave into em uma cláusula de select ou group para criar um identificador temporário que armazena uma consulta.
Faça isso quando você deve executar operações de consulta adicional em uma consulta após um agrupamento ou selecionar a operação.
No seguinte exemplo countries são agrupados de acordo com população em intervalos de 10 milhões.
Depois que esses grupos estiverem cláusulas criado, adicionais filtro-out de alguns grupos e, em seguida, classificar os grupos em crescente da ordem.
Para executar essas operações adicionais, a continuação representada por countryGroup é necessária.
var percentileQuery =
country countries
percentile = () country.Population / 10000000
country percentile countryGroup
countryGroup.Key >= 20
countryGroup.Key
countryGroup;
(var grouping percentileQuery)
{
Console.WriteLine(grouping.Key);
(var country grouping)
Console.WriteLine(country.Name + + country.Population);
}
For more information, see em (Referência C#).
Filtragem, classificação e ingressando em
Entre a cláusula from inicial e o final select ou group cláusula, Tudo as outras cláusulas (where, join, orderby, from, let) são opcionais.
Qualquer um das cláusulas opcionais pode ser usada zero vezes ou Múltiplo horas em um Mensagem de consulta.
onde cláusula
Use a cláusula where para Filtro elementos dos dados de origem com base em um ou mais expressões predicados.
A cláusula where no exemplo a seguir tem dois predicados.
IEnumerable<City> queryCityPop =
city cities
city.Population < 200000 && city.Population > 100000
city;
Para obter mais informações, consulte onde cláusula (Referência C#).
orderby cláusula
Use a cláusula orderby para classificar os resultados em ordem crescente ou decrescente.
Você também pode especificar ordens de Classificar secundária.
O exemplo a seguir executa uma Classificar primária nos objetos country , usando a propriedade Area.
Ele, em seguida, executa uma Classificar secundária, usando a propriedade Population.
IEnumerable<Country> querySortedCountries =
country countries
country.Area > 500000, country.Population
country;
A palavra-chave ascending é opcional; ele é a ordem de Classificar padrão se nenhuma ordem é especificada.
For more information, see cláusula orderby (Referência C#).
Cláusula de Junção
Use a cláusula de join para associar e / ou combinar elementos de uma Origem de dados com elementos de Origem de dados de outro com base em uma comparação de igualdade entre chaves especificadas em cada elemento.
Em LINQ, Junção operações são executadas em seqüências de objetos cujos elementos são tipos diferentes.
Após você ter ingressado duas seqüências, você deve usar uma instrução de select ou group para especificar qual elemento para armazenar na seqüência de saída.
Você também pode usar um tipo anônimo para combinar propriedades de cada conjunto de elementos associados em um novo tipo para a seqüência de saída.
O exemplo a seguir associa prod objetos cuja propriedade Category corresponde a uma das categorias a matriz de Cadeia de Caracteres categories.
Produtos cujo Category não coincide com qualquer Cadeia de Caracteres em categories são filtrados.
A instrução select projetos um novo tipo cujas propriedades são obtidas do cat e prod.
var categoryQuery =
cat categories
prod products cat prod.Category
{ Category = cat, Name = prod.Name };
Você também pode executar uma Junção de AAgruparar, armazenando os resultados da operação join em um Temporário variável usando o na palavra-chave.
For more information, see (Referência C#) de cláusula de Junção.
permitir que a cláusula
Use a cláusula let para armazenar o resultado de uma expressão como uma chamada de método em uma Novo variável de intervalo.
No exemplo a seguir, a variável de intervalo s armazena primeiro elemento da matriz de Cadeia de Caracteres retornada por Split.
string[] names = { , , , };
IEnumerable<string> queryFirstNames =
name names
firstName = name.Split( [] { ' ' })[0]
firstName;
(string s queryFirstNames)
Console.Write(s + );
For more information, see permitir que a cláusula (Referência C#).
Subconsultas em uma expressão de consulta
Uma cláusula de consulta propriamente dito pode conter uma expressão de consulta, que às vezes é chamada como uma de subconsulta .
Cada subconsulta começa com sua própria cláusula from que necessariamente não aponta para a mesma Origem de dados na Primeiro cláusula from.
Por exemplo, a consulta a seguir mostra uma expressão de consulta que é usada na instrução Selecionar para recuperar os resultados de uma operação de agrupamento.
var queryGroupMax =
student students
student student.GradeLevel studentGroup
{
Level = studentGroup.Key,
HighestScore =
( student2 studentGroup
student2.Scores.Average())
.Max()
};
For more information, see Como: Executar uma subconsulta em uma operação de agrupamento (Guia de programação C#).
 Consulte também
Conceitos
Referência
Outros recursos
|