linq根据其他表中的where条件选择一个值

时间:2016-06-08 20:10:32

标签: c# linq linq-to-sql linq-to-entities linq-to-objects

我有这个问题:

 var result = (from game in db.Games
                    join gameevent in db.Events
                        on game.GameId equals gameevent.GameId into events
                    from _event in events
                    join _targetObjects in db.TargetObjects
                        on _event.TargetObject equals _targetObjects.TargetObjectId into targetss
                    where game.userId == userId
                    select new ProfileViewModel
                    {
                        record = events.Where(s => s.TargetObjectId == _event.TargetObject && _event.EventType == 35).Select(/* Here I want to select a value from targetss, field called TargetName */).ToList()
                    }).First();

如您所见,我想根据其他表中的where子句获取值。这可能在选择新部分吗?

我想根据与事件表中的targetObjectId匹配的targetObjectId获取targetObject的名称,事件类型也应为35。

有什么建议吗?

谢谢,Laziale

1 个答案:

答案 0 :(得分:1)

如果查询开始变得过于复杂,那么值得将其分成几部分。

在我的下面的例子中,我使用LINQ的扩展方法语法而不是查询关键字,因为它更容易使用。

// First we collect the relevant games.
var games =
    db
        .Games
        .Where(game => game.UserId == userId);

// Then we collect the events of the collected games that have the specified event type.
var events = 
    db
        .Events
        .Join(
            games,
            gameEvent => gameEvent.GameId,
            game => game.GameId,
            (gameEvent, game) => gameEvent
        )
        .Where(gameEvent => gameEvent.EventType == 35);

// Then we collect the target objects based on the collected events.
var targetObjects =
    db
        .TargetObjects
        .Join(
            events,
            targetObject => targetObject.TargetObjectId,
            gameEvent => gameEvent.TargetObjectId,
            (targetObject, gameEvent) => targetObject
        );

// Last we select the target name from the collected target objects.
var records =
    targetObjects
        .Select(targetObject => targetObject.TargetName)
        .ToList(); // The query will be executed at this point.

这可能不是您想要做的,但希望它有所帮助。

如果没有,那么请说明ProfileViewModel应该具有哪些数据以及应该选择哪个数据集,因为我对这种语法不是很熟悉。