English 中文(简体)
使用LINQ执行左外部联接
原标题:Using LINQ to perform a left outer join
  • 时间:2011-02-15 11:15:15
  •  标签:
  • c#
  • linq

我正在尝试构建一个列表,该列表包含一个列表中的所有对象,但如果该对象存在于另一列表中,则会更新特定的属性。

首先,我创建了一个所有可能的“选项”列表。然后,我想更新此列表中的任何项目的“选定”属性,这些项目也存在于我创建的另一个“选项”列表中。我希望下面的代码能起作用,但我得到了异常“对象引用未设置为对象的实例”。

        var query = from o in AllOptions
                    join so in SelectedOptions on o.Code equals so.Code into newOptions
                    from no in newOptions.DefaultIfEmpty()
                    select new Option
        {
            Name = o.Name,
            Description = o.Description,
            Code = o.Code,
            Applicable = o.Applicable,
            Selected = no.Selected
        };
最佳回答

您从no.中获得异常。在投影中选择语句,当no为null时,它将抛出,因为您正在取消引用null。

当<code>no</code>为null时,您可以通过指定默认值来修复它:

//default to false when no is null
Selected = (no == null) ? false : no.Selected
问题回答

暂无回答




相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签