我有三个列表
List<Project> intProjects = ProjectRepo.GetAllInternalProjects();
List<Project> extProjects = ProjectRepo.GetAllExternalProjects();
List<Project> mgmProjects = ProjectRepo.GetAllManagementProjects();
List<Project> projects = intProjects.Concat(extProjects).Concat(mgmProjects).ToList();
如果我在所有列表中都有项目,它可以正常工作,但当其中一个列表为null value
时,我收到null
个例外。
是的,我可以做一个
if (extProjects != null && mgmpProjects != null && intProjects != null)
...
else if (extProjects == null && mgmpProjects != null && intProjects != null
...
对于所有可能的情况,但是必须有一种更有效的方式来加入列表,即使它们是空的。
所以我的问题是:如何连续列出哪些列表可以为空而不会出错?
答案 0 :(得分:5)
您可以使用??
运算符执行此类操作:
List<Project> empty = new List<Project>();
List<Project> intProjects = ProjectRepo.GetAllInternalProjects() ?? empty;
List<Project> extProjects = ProjectRepo.GetAllExternalProjects() ?? empty;
List<Project> mgmProjects = ProjectRepo.GetAllManagementProjects() ?? empty;
List<Project> projects = intProjects.Concat(extProjects).Concat(mgmProjects).ToList();
答案 1 :(得分:3)
你可以使用像这样的扩展方法
public static class EnumerableExtension
{
public static IEnumerable<TSource> ConcatOrSkipNull<TSource>(this IEnumerable<TSource> first, IEnumerable<TSource> second)
{
if (first == null)
first = new List<TSource>();
if (second == null)
return first;
return first.Concat(second);
}
}
然后将代码重写为:
var projects = intProjects
.ConcatOrSkipNull(extProjects)
.ConcatOrSkipNull(mgmProjects)
.ToList();
答案 2 :(得分:1)
在ProjectRepo中,如果找不到结果,请确保函数GetAllInternalProjects()
,GetAllExternalProjects()
,GetAllManagementProjects()
都返回空列表。对于返回列表的函数,我在函数开头初始化返回值,然后根据需要对该列表执行某些操作,并始终返回该值。这样,函数将始终返回列表对象,空或非空。这应该清理你的代码。
以下示例:
List<object> GetAllInternalProjects(){
List<object> results = new List<object>();
/do something here
return results;
}
答案 3 :(得分:1)
不一定有效,但不需要太多打字:
List<Project> projects = new[] { intProjects, extProjects, mgmProjects }
.Where(list => list != null)
.SelectMany(_ => _)
.ToList();
答案 4 :(得分:1)
另一种可能性是像
这样的扩展方法 public static partial class EnumerableExtensions {
public static IEnumerable<T> EmptyIfNull<T>(this IEnumerable<T> source) {
return source ?? Enumerable.Empty<T>();
}
}
所以你可以把
List<Project> projects = intProjects
.EmptyIfNull()
.Concat(extProjects.EmptyIfNull())
.Concat(mgmProjects.EmptyIfNull())
.ToList();
更好的方法是修改GetAllInternalProjects()
,GetAllExternalProjects()
和ProjectRepo.GetAllManagementProjects()
方法:这些方法必须始终返回 not null
集合(可以是空,但是)