将SQL语句转换为Linq

时间:2009-07-22 07:13:11

标签: c# linq-to-sql

如何将以下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 }
);

2 个答案:

答案 0 :(得分:0)

LINQ to SQL将帮助您根据需要获得尽可能多的数据,因此在内存中使用附加语句对其进行重新排序不应该是性能损失。当然,这次它将成为对象的LINQ。

您是否还尝试过上次联盟后致电OrderBy()OrderByDescending()

答案 1 :(得分:0)

两个想法;使用UNION ALL.Concat(...).Union(...)更合适。

二;如有必要,您可以在LINQ-to-Objects中单独进行排序:

var origQry = ...

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

然后这将在内存中执行order-by。