LINQ to Entities - 按数组排序

LINQ to Entities - sort by array

我有以下代码:

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

所以,我 select 来自 'states' 变量的所有状态的附加信息。它有效,但我需要获得与 'states' 变量中相同的顺序。如何排序?它需要 IComparer 对象,但我无法想象在我的情况下如何编写它

枚举 states 而不是 _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
              });

您可以在 OrderBy 函数中使用 IndexOf 函数。假设您在两个列表中都有一个相同的 id 字段。假设在这种情况下 id 被称为 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();

如果您想要原始顺序,您可以这样做:

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


 }