Search code examples
c#linqlinq-to-entitiesicomparableicomparer

LINQ to Entities - sort by array


I have the following code:

    public List<OversizeElement> GetOversizeRegulations(List<string> states)
    {
        var tmpList = (from i in _db.States
                       where states.Any(p=>i.Name == p)
                       select new
                       {
                           StateID = i.ID,
                           StateName = i.Name,
                           StateShortName = i.ShortName
                       }).ToList();

so, I select additional information for all states from 'states' variable. It works, but I need to get the same order, as in the 'states' variable. How to sort it? It requires IComparer object, but I can't imagine how to write it in my case


Solution

  • If you want the original ordering you can do something like:

    public List<Destination> GetOversizeRegulations(List<string> states)
    {
    
            var tmpDictionary = (from i in _db.States
                                 where states.Contains(i.Name)
                                 select new
                                          {
                                            StateID = i.Id,
                                            StateName = i.Name,
                                            StateShortName = i.ShartName
                                          }
                                  ).ToDictionary(k => k.StateName, k => k);
    
            var result = states
                        .Where(m=>tmpDictionary.ContainsKey(m))
                        .Select(m => tmpDictionary[m]).ToList();
    
    
     }