Rahul Uttarkar
Rahul Uttarkar

Reputation: 3645

How to OrderBy() as per the order requested in distinct string list

How to use OrderBy for shaping output in the same order as per the requested distinct list

    public DataCollectionList GetLatestDataCollection(List<string> requestedDataPointList)
    {
        var dataPoints = _context.DataPoints.Where(c => requestedDataPointList.Contains(c.dataPointName))
                                 .OrderBy(----------)  //TODO: RE-ORDER IN THE SAME ORDER AS REQUESTED requestedDataPointList
                                 .ToList();        
        
         
        dataPoints.ForEach(dp => 
        {
           ....
        });

    }

Upvotes: 0

Views: 81

Answers (2)

Gert Arnold
Gert Arnold

Reputation: 109253

It think the fastest method is to join the result back with the request list. This makes use of the fact that LINQ's join preserves the sort order of the first list:

var dataPoints = _context.DataPoints
    .Where(c => requestedDataPointList.Contains(c.dataPointName))
    .ToList();

var ordered = from n in requestedDataPointList
              join dp in dataPoints on n equals dp.dataPointName
              select dp;

foreach (var dataPoint in ordered)
{
    ...
}

This doesn't involve any ordering, joining does it all, which will be close to O(n).

Another fast method consists of creating a dictionary of sequence numbers:

var indexes = requestedDataPointList
    .Select((n, i) => new { n, i }).ToDictionary(x => x.n, x => x.i);
var ordered = dataPoints.OrderBy(dp => indexes[dp.dataPointName]);

Upvotes: 1

NetMage
NetMage

Reputation: 26926

Do the sorting on the client side:

public DataCollectionList GetLatestDataCollection(List<string> requestedDataPointList)
{
    var dataPoints = _context.DataPoints.Where(c => requestedDataPointList.Contains(c.dataPointName))
                             .AsEnumerable()
                             .OrderBy(requestedDataPointList.IndexOf(c.dataPointName));        
    
    foreach (var dp in dataPoints)
    {
       ....
    });

}

NOTE: Also, I don't think ToList().ForEach() is ever better than foreach ().

Upvotes: 1

Related Questions