EF. How to union tables, sort rows, and get top en

2019-05-10 01:02发布

问题:

I want to union records from 2 tables, sort them, and read TOP rows from result set.

T1
--------
Id, Timestamp, Text1

T2
--------
Id, Timestamp, Text2

With SQL it can be done this way:

SELECT TOP 10 * FROM
(
    SELECT 
        [Timestamp], 
        [Text1] 

    FROM 
        T1

    UNION

    SELECT 
        [Timestamp], 
        [Text2]

    FROM 
        T2
) as x

ORDER BY [Timestamp]

Q: How can I do that task using EF linq?

回答1:

You need an anonymous type with the same property names and types before you can do an Union operation:

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


回答2:

How about something like:

var top10 = EFentity.t2.Union(EFentity.t1.ToList()).OrderBy(t=>t.Timestamp).ToList().Take(10);