Oleg Sh
Oleg Sh

Reputation: 9013

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

Upvotes: 1

Views: 201

Answers (3)

George Vovos
George Vovos

Reputation: 7618

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();


 }

Upvotes: 2

Matt Spinks
Matt Spinks

Reputation: 6698

You can use the IndexOf function within your OrderBy function. Assuming you have an id field of some sort in both lists that are identical. Let's say in this instance that id is called StateId:

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
                   }).OrderBy(s => states.Select(x => x.StateId).IndexOf(s.StateId)).ToList();

Upvotes: 0

Matias Cicero
Matias Cicero

Reputation: 26281

Enumerate states instead of _db.States:

var tmpList = states
              .Select(s => _db.States.SingleOrDefault(st => st.Name == s))
              .Where(s => s != null)
              .Select(new
              {
                  StateID = s.ID,
                  StateName = s.Name,
                  StateShortName = s.ShortName
              });

Upvotes: 0

Related Questions