2013-03-20 27 views
-1

假设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      
    } 
} 
+3

你不应该抛出像这样的例外。一个空的'List'不是一个例外。 – Sam 2013-03-20 14:51:51

+1

为什么你需要为此抛出异常?你可以缩短它到'theList.Any()',所以它不需要遍历整个列表。 – Arran 2013-03-20 14:52:25

+0

为了我的代码,一个空的List是一个例外。但我会更新我的文章,因为我不希望这成为这个问题的焦点。 – 2013-03-20 14:55:51

回答

0

如果你真的想做到这一点,你可以创建一个扩展方法(如你说自己)。

class Program { 
    static void Main(string[] args) { 
     List<string> data = new List<string>(); 
     foreach (var item in data.FailIfEmpty(new Exception("List is empty"))) { 
      // do stuff 
     } 
    } 
} 
public static class Extensions { 
    public static IEnumerable<T> FailIfEmpty<T>(this IEnumerable<T> collection, Exception exception) { 
     if (!collection.Any()) { 
      throw exception; 
     } 
     return collection; 
    } 
} 
+0

这就是我正在寻找的。我知道在我的问题我假设收集不是null,但我会在FailIfEmpty方法中添加额外的逻辑来检查空值。谢谢! – 2013-03-20 15:00:42

0

可以预先抛出异常,而无需编写的else块:

if(mylist.Count == 0) 
    throw new Exception("Test"); 

foreach(var currItem in mylist) 
    currItem.DoStuff(); 

的执行流不会到达循环,如果异常已经提高。