2012-08-05 45 views
1

問題: 任何人都可以告訴我如何在linq中返回值。 我想返回一個RadToolBarButtons集合,並在創建時爲它們賦值。在linq中的yield返回foreach

代碼: 我試圖在兩個方面:

IEnumerable<RadToolBarButton> collection = ContextMenuColumn.ToList() 
     .ForEach(x => yield return new RadToolBarButton() { Value = x }); 

錯誤11無法隱式轉換類型 '無效' 到 'System.Collections.Generic.IEnumerable'

IEnumerable<RadToolBarButton> collection = 
    ContextMenuColumn.SelectMany<string,IEnumerable<RadToolBarButton>>(
     x => new RadToolBarButton() { Value = x }); 

錯誤11不能隱將類型'Telerik.Web.UI.RadToolBarButton'轉換爲'System.Collections.Generic.IEnumerable>'。一個顯式轉換存在(是否缺少強制轉換?)

回答

3

您應該使用Select而不是ForEach,它確實你在找什麼。

IEnumerable<RadToolBarButton> collection = ContextMenuColumn.ToList() 
    .Select(x => new RadToolBarButton { Value = x }); 

我不知道,如果內ToList是必要的,你可以逃脫一Cast<T>代替物化中間列表。

+0

哦,謝謝它的工作。 :) – Wajahat 2012-08-05 11:02:14

0

使用Select,而不是ForEach,它會做yield returm