1

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

Oleg Sh
  • 8,496
  • 17
  • 89
  • 159

3 Answers3

2

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


 }
George Vovos
  • 7,563
  • 2
  • 22
  • 45
0

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
              });
Matias Cicero
  • 25,439
  • 13
  • 82
  • 154
0

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();
Matt Spinks
  • 6,380
  • 3
  • 28
  • 47