代码之家  ›  专栏  ›  技术社区  ›  Keltex

如何按照提供的ID顺序从Linq查询中获取结果?

  •  4
  • Keltex  · 技术社区  · 15 年前

    我希望按照向查询传递id的顺序从Linq获取查询结果。所以它看起来像这样:

    var IDs = new int [] { 5, 20, 10 }
    
    var items = from mytable in db.MyTable
                where IDs.Contains(mytable.mytableID)
                orderby // not sure what to do here
                select mytable;
    

    IDs (5, 20, 10).

    (注意这与 this question ,但我希望使用Linq而不是SQL)

    2 回复  |  直到 8 年前
        1
  •  1
  •   abatishchev Karl Johan    15 年前

    我只需要在SQL查询之外执行它。在这种情况下,在SQL Server上完成这项工作实际上没有任何好处。

    var items = (from mytable in db.MyTable
                 where IDs.Contains(mytable.mytableID)
                 select mytable)
                .ToArray()
                .OrderBy(x => Array.IndexOf(ids, x.mytableID));
    
        2
  •  1
  •   dtb    15 年前

    var ids = new int [] { 5, 20, 10 };
    
    var result = from item in items
                 where Array.IndexOf(ids, item.Id) >= 0
                 orderby Array.IndexOf(ids, item.Id)
                 select item;