2012-03-14 47 views
2

我有可以返回的項目列表或像這樣如下(僞)單個項目的功能如何返回IEnumerable的<T>單個項目

IEnumerable<T> getItems() 
{ 
    if (someCondition.Which.Yields.One.Item) 
    { 
     List<T> rc = new List<T>(); 
     rc.Add(MyRC); 

     foreach(var i in rc) 
      yield return rc; 
    } 
    else 
    { 
     foreach(var i in myList) 
      yield return i; 
    } 
} 

第1部分似乎有點缺憾,希望使其可讀

+0

卡住試圖選擇正確的答案,任何想法? – Kumar 2012-03-15 19:21:43

回答

8
IEnumerable<T> getItems() 
{ 
    if (someCondition.Which.Yields.One.Item) 
    { 
     yield return MyRC; 
    } 
    else 
    { 
     foreach(var i in myList) 
      yield return i; 
    } 
} 
6

你不需要做任何事情:

yield return MyRC; 

你正常返回的項目一個接一個,一個集合中不進行分組。

但是,如果它是一個IEnumerable<IList<T>>那麼它是不同的。簡單地返回此:

yield return new[] { singleItem }; 

,或者如果它是一個IEnumerable<List<T>>然後

yield return new List<T> { singleItem }; 
4

List<T>是不必要的。 yield關鍵字存在的原因。

IEnumerable<T> getItems(){ 
    if (someCondition.Which.Yields.One.Item) 
    { 
     yield return MyRC; 
    } 
    else 
    { 
     foreach(var i in myList) 
      yield return i; 
    } 
} 
+0

嗯,收益率回報myRC沒有更早的工作,現在它!深夜我猜! – Kumar 2012-03-14 16:35:33

2

關於什麼:

IEnumerable<T> getItems(){ 
    if (someCondition.Which.Yields.One.Item) 
    { 
     yield return MyRC; 
    } 
    else 
    { 
     foreach(var i in myList) 
      yield return i; 
    } 
6

目前尚不清楚,你需要首先使用迭代器塊。你是否需要/希望推遲執行?如果調用者多次迭代返回的序列,您是否需要/想要多次評估條件?如果沒有,只需使用:

IEnumerable<T> GetItems() 
{ 
    if (someCondition.Which.Yields.One.Item) 
    { 
     return Enumerable.Repeat(MyRC, 1); 
    } 
    else 
    { 
     // You *could* just return myList, but 
     // that would allow callers to mess with it. 
     return myList.Select(x => x); 
    } 
} 
+0

myList是一個佔位符,用於辦公室com的func的佔位符,它返回poco的所以必須使用yield return!對此有何想法? http://stackoverflow.com/questions/9696115/disposableaction-and-marshal-releasecomobject – Kumar 2012-03-14 16:26:37

+0

@Kumar:你爲什麼不直接建立這個列表呢?再次 - 你需要延期執行嗎? – 2012-03-14 16:27:57

+0

不,不需要延遲的exec,但需要能夠處理大量的郵件數據,每次只能處理一個附件,因此收益率高,而且肯定需要清理com引用 – Kumar 2012-03-14 16:40:21

相關問題