Linq按列表顺序从两个表中选择

时间:2012-11-17 09:00:04

标签: c# sql linq select sql-order-by

我在DB中有两个表,我想从中选择。在其中一个'事件'中我有事件(Id,开始,结束,类型),另一个我有'Events_before_after',我收集与'Events'中的一些事件相关联的事件 - (Id,EventId,开始,结束,类型) 我还有一个事件ID列表,我需要通过它来选择查询中的事件。

这就是我所拥有的:

List<int> orderIds = ...

from order in orderIds
join event in events order on order equals event.id
select new DataEvent ()
{
    eventId = event.Id,
    start = event.start,
    end = event.end,
    type = event.type
}).Concat
from eventOther in Events_before_after
select new DataEvent ()
{
    eventId = eventOther.Id,
    start = eventOther.start,
    end = eventOther.end,
    type = eventOther.type
}

是否可以订购第二个选择?我的意思是 - 有没有办法按eventId订购,链接到'活动'?

我需要的是:

event1
event2
eventBefore3
event3
eventAfter3

我所拥有的是:

event1
event2
event3
eventBefore3
eventAfter3

2 个答案:

答案 0 :(得分:3)

你可以这样做:

 //your query
 ...
from eventOther in Events_before_after
select new DataEvent ()
{
    eventId = eventOther.Id,
    start = eventOther.start,
    end = eventOther.end,
    type = eventOther.type
}
into NewEvent
order by NewEvent.eventId
select NewEvent;

答案 1 :(得分:2)

如果我得到你的要点,你想要将给定键上的相关事件组合在一起,对它们进行排序,然后根据给定的键排序进行投影和展平....如果你想这样做,请尝试以下方法:

var orderedEvents = orderIds.Join(
                     //Construct Groups 
                     events.GroupBy( e => e.Id)
                           .GroupJoin( Events_before_after,
                                       g => g.Key,
                                       e => e.EventId,
                                       (gEvent, gEventBA) => new { Key = gEvent.Key,
                                       EventGroup = 
                                       gEvent.Select( e => new DataEvent ()
                                                     {
                                                      eventId = e.Id,
                                                      start = e.start,
                                                      end = e.end,
                                                      type = e.type
                                                     })
                                              .Concat( gEventBA.Select( e => new DataEvent ()
                                                                {
                                                                 eventId = e.Id,
                                                                 start = e.start,
                                                                 end = e.end,
                                                                 type = e.type
                                                                }))
                                              .OrderBy(e => e.eventId)),
                      //Project along keys
                      o => o,
                      anon => anon.Key,
                      (o,anon) => anon.EventGroup)
                      //Flatten groups
                           .SelectMany( g => g);