1

I'm trying to execute the follow code and it works fine if myObject is != null but throws a "value cannot be null" error if myObject is null. Ideally, if myObject is null then I'd like to just have the HashSet have a single value of 0.

var ids = new HashSet<int>(myObject.Select(p => p.ID));

I've tried a couple different things. I'm not sure why I thought this would work.

var ids = new HashSet<int>(myObject.Select(p => p.ID).Where(p => p != null));

and this which seemed like it should work.

var ids = new HashSet<int>(myObject.Select(p => (p == null) ? 0 : p.ID));

Finally this worked but it seems like there's got to be a better way.

var ids = new HashSet<int>(myObject!= null ? myObject.Select(p => p.ID) : new int[] {0});

Anyone have a better way to do this?

4

2 回答 2

2

现在,您的答案可以稍微清理一下:

var ids = new HashSet<int>(myObject?.Select(p => p.ID) ?? new [] {0});
于 2017-11-15T17:37:59.933 回答
1

如果 myObject 为空,您的代码将转换为

var ids = new HashSet<int>(null.Select(p => p.ID));

您不能使用 Select 扩展方法关闭 null。

你的选择

var ids = new HashSet<int>(myObject!= null ? myObject.Select(p => p.ID) : new int[] {0});

是我所知道的满足您要求的最紧凑的形式,尽管如果您愿意,当然可以将这种复杂性隐藏在方法或扩展方法中。

于 2012-07-24T02:42:34.557 回答