Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set values with a Linq-Query?

Tags:

c#

.net

linq

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?

like image 959
TalkingCode Avatar asked Nov 20 '09 15:11

TalkingCode


People also ask

How to get data from LINQ query?

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 ).

How to write select query using LINQ?

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.

How to select LINQ C#?

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.

How do LINQ queries work?

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.


1 Answers

Might this work?

int rankPosition = 1;
var sortedListKFZ = listKFZ.OrderBy(r => r.Price).Select(r => {
    r.MesaAdvertNumber = ++rankPosition;
    return r;
});
like image 9
David Hedlund Avatar answered Oct 19 '22 11:10

David Hedlund