简体   繁体   中英

How to use lambda expression for below code block?

I am writing a piece of code in order to get values from the server. There are multiple code lines and need to do the same thing using lambda expressions. This is the code I have tried and please help to rewrite this code using lambda expressions.

var newDocuments = result?.DocumentQueryResults.OrderBy(d => context.GetParams().GetAllDocumentIds().ToList().IndexOf(d.Document.Id)).ToList();

var test = new List<HealthRecord>();

foreach (DocumentQueryResult item in newDocuments)
   {
         test.Add(item.Document);
   }

I believe you're looking for something like this:

// Cache the sort parameters, as suggested by Caius Jard:
var sortParams = context.GetParams()
    .GetAllDocumentIds()
    .AsEnumerable()
    .Select((id, index) => new { id, index })
    .ToDictionary(x => x.id, x => x.index);

var test = result?.DocumentQueryResults
    .OrderBy(d => sortParams[d.Document.Id])
    .Select(d => d.Document)
    .ToList();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM