我希望从两个表中合并记录,对它们进行排序,并从结果集中读取TOP行。
T1
--------
Id, Timestamp, Text1
T2
--------
Id, Timestamp, Text2
使用SQL可以这样做:
SELECT TOP 10 * FROM
(
SELECT
[Timestamp],
[Text1]
FROM
T1
UNION
SELECT
[Timestamp],
[Text2]
FROM
T2
) as x
ORDER BY [Timestamp]
问:如何使用EF linq执行该任务?
答案 0 :(得分:7)
在执行Union
操作之前,您需要具有相同属性名称和类型的匿名类型:
var t1List = from a in allT1
select new
{
TimeStamp = a.TimeStamp,
Text = a.Text1
};
var t2List = from b in allT2
select new
{
TimeStamp = b.TimeStamp,
Text = b.Text2
};
var result = t1List.Union(t2List).OrderBy(ab => ab.TimeStamp).Take(10);
答案 1 :(得分:0)
如下:
var top10 = EFentity.t2.Union(EFentity.t1.ToList()).OrderBy(t=>t.Timestamp).ToList().Take(10);