【问题标题】:Linq select a value based on where condition from other tableLinq 根据其他表中的条件选择一个值
【发布时间】:2016-06-08 20:10:31
【问题描述】:

我有这个问题:

 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 子句获取值。在选择新部分中可能吗?

我想根据与 events 表中的 targetObjectId 匹配的 targetObjectId 获取 targetObject 的名称,并且事件类型应该是 35。

【问题讨论】:

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


    【解决方案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 应该准确拥有哪些数据以及应该从哪个数据集中选择它,因为我不太熟悉这种语法。

    【讨论】:

      猜你喜欢
      • 2022-09-30
      • 2019-12-13
      • 1970-01-01
      • 2014-01-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-16
      • 1970-01-01
      相关资源
      最近更新 更多