2010-05-26 36 views
4

我期待从Linq返回查询结果,以便将ID传递给查询。因此,这将是这个样子:如何按照我提供的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)

+0

它的LINQ没有链接;) – 2010-05-26 22:42:38

+0

@Abe-谢谢你的追捕! – Keltex 2010-05-26 23:45:57

+0

愚蠢的拼写检查软件 – ecounysis 2010-05-27 04:55:43

回答

1

我只是在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)); 
1

这应该一起工作LINQ到对象;虽然我不确定它是否与LINQ-to-SQL一样:

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; 
相关问题