In my application I have a list of items I need to sort by price and set a rank/position index for each item. I need to store the rank because the price may change afterward. At the moment I am doing it like this:
var sortedlistKFZ = from res in listKFZ orderby res.Price select res;
if (sortedlistKFZ.Any())
{
int rankPosition = 1;
foreach (Result kfz in sortedlistKFZ)
{
kfz.MesaAdvertNumber = rankPosition;
rankPosition++;
}
}
Is there a shorter way to do it?
In a LINQ query, the first step is to specify the data source. In C# as in most programming languages a variable must be declared before it can be used. In a LINQ query, the from clause comes first in order to introduce the data source ( customers ) and the range variable ( cust ).
LINQ query syntax always ends with a Select or Group clause. The Select clause is used to shape the data. You can select the whole object as it is or only some properties of it. In the above example, we selected the each resulted string elements.
Select(<selector>) method The Select() method invokes the provided selector delegate on each element of the source IEnumerable<T> sequence, and returns a new result IEnumerable<U> sequence containing the output of each invocation.
In a LINQ query, you are always working with objects. You use the same basic coding patterns to query and transform data in XML documents, SQL databases, ADO.NET Datasets, . NET collections, and any other format for which a LINQ provider is available.
Might this work?
int rankPosition = 1;
var sortedListKFZ = listKFZ.OrderBy(r => r.Price).Select(r => {
r.MesaAdvertNumber = ++rankPosition;
return r;
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With