簡體   English   中英

將SQL語句轉換為Linq

[英]Convert SQL statement to Linq

如何將以下SQL語句轉換為LinqToSQL語句?

select field, 1 as ordering from table where field2 = condition1
union all
select field, 7 as ordering from table where field2 = condition2
union all
select field, 3 as ordering from table where field2 = condition3
union all
select field, 2 as ordering from table where field2 = condition4
order by ordering

實際上,我只是加入幾個查詢,並根據行的原點對結果集進行排序。

我可以按如下所示管理聯合,但似乎無法讓LinqToSQL對整個結果集進行排序,而只能讓它對每個單獨的查詢進行排序。

from t in table
where
condition
select new { field, ordering = 1 }
).Union
(
from t2 in table2
where
condition
select new { field ordering = 7 }
).Union
(
from t3 in table3
where
condition
select new { field ordering = 3 }
).Union
(
from t4 in table4
where
condition
select new { field ordering = 2 }
);

LINQ to SQL將幫助您根據需要在網絡上獲取盡可能多的數據,因此使用附加語句在內存中對其進行重新排序不會對性能造成影響。 當然這次是LINQ to Objects。

您是否還嘗試過在上一個聯合之后調用OrderBy()OrderByDescending()

兩個想法; 使用UNION ALL.Concat(...).Union(...)更合適。

第二; 您可以根據需要在LINQ-to-Objects中分別進行訂購:

var origQry = ...

var qry = origQry.AsEnumerable().OrderBy(x => x.ordering);

然后,這將在內存中進行排序。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM