【问题标题】:Linq join that accepts null values [duplicate]接受空值的Linq连接[重复]
【发布时间】:2014-11-25 02:52:41
【问题描述】:

我有一个这样的 Linq 查询:

var items = from v in work.GetRepo<VW_V>().Query
        join k in work.GetRepo<K>().Query on v.Loc_Id equals k.Id
        join p in work.GetRepo<P>().Query on v.Peer_Id equals p.Id
        join tt in work.GetRepo<TT>().Query on v.Item_Id equals tt.Id
        select (new MyModel
        {
            Id = v.Id,
            Location = k != null ? k.Name : string.Empty,
            ItemName = tt.Name,
            Peer = p != null ? p.Name : string.Empty,
        });

此查询工作正常。但我想记录其中一些没有 Peer 的记录。我怎样才能做到这一点?此查询返回只有 Peers 的记录,我如何才能拥有既有 Peers 而没有 Peers 的记录。如果该记录中存在对等点,我想显示对等点的名称。谢谢。

【问题讨论】:

标签: c# linq


【解决方案1】:
var items = from v in work.GetRepo<VW_V>().Query

            join k in work.GetRepo<K>().Query 
              on v.Loc_Id equals k.Id

            join p in work.GetRepo<P>().Query 
              on v.Peer_Id equals p.Id
            into pJoinData 
            from pJoinRecord in pJoinData.DefaultIfEmpty( )

            join tt in work.GetRepo<TT>().Query 
              on v.Item_Id equals tt.Id

            select (new MyModel
            {
                Id = v.Id,
                Location = k != null ? k.Name : string.Empty,
                ItemName = tt.Name,
                Peer = pJoinRecord != null ? pJoinRecord.Name : string.Empty,
            });

【讨论】:

    【解决方案2】:

    它被称为左outer join。试试:

    var items = from v in work.GetRepo<VW_V>().Query
            join k in work.GetRepo<K>().Query on v.Loc_Id equals k.Id
            join p in work.GetRepo<P>().Query on v.Peer_Id equals p.Id into subpeer_j
            from subpeer in subpeer_j.DefaultIfEmpty()
            join tt in work.GetRepo<TT>().Query on v.Item_Id equals tt.Id
            select (new MyModel
            {
                Id = v.Id,
                Location = k != null ? k.Name : string.Empty,
                ItemName = tt.Name,
                Peer = subpeer != null ? subpeer.Name : string.Empty,
            });
    

    【讨论】:

      猜你喜欢
      • 2019-01-29
      • 2014-04-08
      • 1970-01-01
      • 2018-05-30
      • 1970-01-01
      • 2017-06-10
      • 2021-05-06
      • 2017-09-28
      • 1970-01-01
      相关资源
      最近更新 更多