我有一個ID數組,依次使用這些ID然後發出LINQ查詢,但是我希望LINQ查詢的結果以與數組中的ID相同的順序返回。如何使用數組訂購linq結果?
例子:
int[] ids = new [] {10, 9, 8, 7};
var query = from row in context.Table where ids.Contains(row.Id) select row;
我怎麼能確保所獲得的項目都在同一順序的數組中?
我有一個ID數組,依次使用這些ID然後發出LINQ查詢,但是我希望LINQ查詢的結果以與數組中的ID相同的順序返回。如何使用數組訂購linq結果?
例子:
int[] ids = new [] {10, 9, 8, 7};
var query = from row in context.Table where ids.Contains(row.Id) select row;
我怎麼能確保所獲得的項目都在同一順序的數組中?
您可以通過索引順序排他們Id
在ids
:
var query = from row in context.Table
where ids.Contains(row.Id)
orderby Array.IndexOf(ids, row.Id)
select row;
我不知道,如果LINQ到SQL供應商支持這個;您可能需要執行使用LINQ到對象的排序:
var query = from row in context.Table
where ids.Contains(row.Id)
select row;
var orderedQuery = from row in query.AsEnumerable()
orderby Array.IndexOf(ids, row.Id)
select row;
或
var orderedQuery = context.Table
.Where(row => ids.Contains(row.Id))
.AsEnumerable()
.OrderBy(row => Array.IndexOf(ids, row.Id));
你有沒有閱讀正確的問題?問題不在於如何排序查詢,而是如何根據外部數組中值的順序進行排序。 – Mantorok
您可以通過IDS枚舉,然後尋找合適的表項:
// if table contains multiple rows per id
var resultSet = ids.SelectMany(id => context.Table.Where(tbl => tbl == id));
// if table contains one row per id
var resultSet = ids.Select(id => context.Table.Where(tbl => tbl == id).Single());
爲什麼不從Ids中選擇,然後在表中搜索適當的行?可能是我錯過了一些問題的點... – sll
完美的答案,謝謝。 – Mantorok
@sll:選擇多行的一個查詢可能比多個查詢分別選擇一行更有效。 – dtb