【问题标题】:Issues with null entries using LINQ Join使用 LINQ Join 的空条目问题
【发布时间】:2013-04-12 19:16:48
【问题描述】:

在过去的几天里,我一直在为此苦苦挣扎,在进行了详尽的谷歌搜索之后,我还没有弄清楚该怎么做。我对 LINQ 和 C# 非常陌生。基本上,我正在尝试加入两个表,都是一个表,但是我尝试加入的列确实包含空值。然后将另一个表的子集加入该列。

我想要发生的是,在加入后,我从显示的第一个表中获取所有信息,而不是我现在得到的信息,其中只显示了不为空的列。

我知道这是一个特别优雅的解释,所以我将发布一些简化的 puesdo 代码:

tblAsset                    tblLookUps

AssetTag int                Domain String
Type int                    DomainID int
Model int                   Description String

所以表格中的信息类似于:

100, 1, 1                   TYPE,  1, PC 
101, 1, null                TYPE,  2, Monitor 
102, 1, 2                   MODEL, 1, Old PC
103, 2, null                MODEL, 2, New PC
104, 2, null                MODEL, 3, Old Monitor
105, 2, 3                   MODEL, 4, New Monitor

所以我希望 LINQ 查询给我的是这样的

AssetTag Type TypeDescription Model ModelDescription
  100      1        PC          1        Old PC
  101      1        PC         null       null
  102      1        PC          2        New PC
  103      2      Monitor      null       null
  104      2      Monitor      null       null
  105      2      Monitor        3     Old Monitor

但是目前 LINQ 会返回:

AssetTag Type TypeDescription Model ModelDescription
  100      1        PC          1        Old PC
  102      1        PC          2        New PC
  105      2      Monitor       3      Old Monitor

所以很明显,当尝试加入时,如果值为 null,它会被遗漏,这当然我理解,但是我并不关心它是否为 null,所以非常希望能够看到它!

我当前的 LINQ 如下所示:

  var AllAssets = from assets in dContext.tblAssets
                  join type in dContext.tblLookups.Where(x => x.Domain == "ASTYPE")
                       on assets.Type equals type.DomainID
                  join model in dContext.tblLookups.Where(x => x.Domain == "MODEL") 
                       on assets.Model equals model.DomainID
                  select new Asset
                  {
                   AssetTag = assets.AssetTag
                   TypeID = assets.Type
                   TypeDescription = type.Description
                   ModelID = assets.Model
                   ModelDescription = model.Description
                  }

  return AllAssets;

我试过摆弄 .DefaultIfEmpty() 和其他一些东西,但我没有设法解决它,感觉我已经达到了能力的尽头,任何提示或指针都会很棒!

【问题讨论】:

    标签: linq null left-join


    【解决方案1】:
        var q = from a in tblAssets
                join l in tblLookUps on a.Model equals l.DomainID
                into tblAssettblLookUps
                from l in tblAssettblLookUps.DefaultIfEmpty()
                select new
                {
                    AssetTag  = a.AssetTag,
                    Type = a.Type,                    
                    Model = a.Model
                    ModelDescription = l.Description
                };
    

    试试这样的查询。

    【讨论】:

    • 太完美了!我不知道我是怎么错过第一次的,非常感谢!
    猜你喜欢
    • 2021-11-21
    • 2012-06-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多