假设ienumerable不为null,如果该ienumerable为空,则foreach循环将不会执行。但是,如果集合是空的,我需要运行其他代码。下面是该作品完美示例代码:当enienumerable为空时,在foreach循环中相当于“Else”
List<string> theList = new List<string>() {};
if (theList.Count > 0) {
foreach (var item in theList) {
//do stuff
}
} else {
//throw exception or do whatever else
}
反正是有经外的开箱C#中,扩展方法等,以缩短这个吗?在我的脑子里,我想下面会很酷,但很明显,这是行不通的:
List<string> theList = new List<string>() {};
foreach (var item in theList) {
//do stuff
} else {
//throw exception or do whatever else
}
编辑:我的解决方案感谢洞察力从马腾:如果集合为空或空下面将抛出一个异常(如果你想简单忽略箱子其中收集为null或空,在foreach使用三元运算符)
static class Extension {
public static IEnumerable<T> FailIfNullOrEmpty<T>(this IEnumerable<T> collection) {
if (collection == null || !collection.Any())
throw new Exception("Collection is null or empty");
return collection;
}
}
class Program {
List<string> theList = new List<string>() { "a" };
foreach (var item in theList.FailIfNullOrEmpty()) {
//do stuff
}
}
你不应该抛出像这样的例外。一个空的'List'不是一个例外。 – Sam 2013-03-20 14:51:51
为什么你需要为此抛出异常?你可以缩短它到'theList.Any()',所以它不需要遍历整个列表。 – Arran 2013-03-20 14:52:25
为了我的代码,一个空的List是一个例外。但我会更新我的文章,因为我不希望这成为这个问题的焦点。 – 2013-03-20 14:55:51