以优雅的方式合并两个IEnumerables [英] Merge two IEnumerables in elegant way

查看:50
本文介绍了以优雅的方式合并两个IEnumerables的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个IEnumerable变量,都可以为null.我需要将它们合并到一个列表中.这是直接的方法.

I have two IEnumerable variables, both can be null. I need to merge them into a single list. Here is direct approach.

var ienumerable1 = GetEnumerable1(); 
var ienumerable2 = GetEnumerable2(); 

if(ienumerable1 != null){
   if(ienumerable2 != null){
      return ienumerable1.Union(ienumerable2);
   }
   return ienumerable1;
}
else{
   return ienumerable2;
}

用更少的代码行就能做到这一点吗?

Is there a more elegant way in less lines of code to do this?

推荐答案

只需检查是否为空,然后将 Enumerable.Empty 分配为空.可以使用空合并运算符 一步完成??

Just check for null and assign Enumerable.Empty if it is null. This can be done in one step with the null coalescing operator ??

var ienumerable1 = GetEnumerable1() ?? Enumerable.Empty<WhateverType>();
var ienumerable2 = GetEnumerable2() ?? Enumerable.Empty<WhateverType>(); 

return ienumerable1.Union(ienumerable2);

这篇关于以优雅的方式合并两个IEnumerables的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆