2009-07-22 139 views
1

如何将下列SQL语句转换为LinqToSQL语句?将SQL语句转换为Linq

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 } 
); 

回答

0

的LINQ to SQL将有助于根据需要这样一个额外的语句重新排序在内存中应该不会有性能损失你上线只是尽可能多的数据。当然这次它将是一个LINQ to Objects。

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

+0

这正是我之后 - 谢谢。 – user9659 2009-07-22 07:44:06

0

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

秒;如果需要,您可以在LINQ到对象中单独进行排序:

var origQry = ... 

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

然后这将在内存中执行顺序。