3

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?

alex2k8
  • 42,496
  • 57
  • 170
  • 221

2 Answers2

7

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);
Thomas Li
  • 3,358
  • 18
  • 14
  • I wouldn't say you _need_ an anonymous type. All you need is that both queries return the same type. You could just as easily use your own type that has `TimeStamp` and `Text` properties. – Andy T Jun 23 '14 at 17:59
0

How about something like:

var top10 = EFentity.t2.Union(EFentity.t1.ToList()).OrderBy(t=>t.Timestamp).ToList().Take(10);
Pete
  • 10,651
  • 9
  • 52
  • 74