Home > front end >  Get position of element in collection filtered by a condition
Get position of element in collection filtered by a condition

Time:05-17

I need to get the index (position) of an element when filtered by a condition.

Here is the code to filter by condition:

var rank =  await _dbContext.VwJobSupplierWithScores
    .OrderBy(x => x.CalculatedSpendCurrencyJob) 
    .FirstOrDefaultAsync(x => x.JobId == jobId && x.SupplierKey == supplierKey);

I need to get the position of the element in the collection that returns before .FirstOrDefaultAsync

How can I do this?

CodePudding user response:

You may use the following:

var rankPair =  await _dbContext.VwJobSupplierWithScores
    .OrderBy(x => x.CalculatedSpendCurrencyJob)
    .Select((x, i) => new { item = x, index = i })
    .Where(pair => pair.item.JobId == jobId && pair.item.SupplierKey == supplierKey)
    .FirstOrDefaultAsync();

var rank = rankPair.item;
int index = rankPair.index;
  • Related