Waj*_*hat 3 linq foreach yield return
问题:谁能告诉我如何在 linq.xml 中返回值?我想返回一组 RadToolBarButtons 并在创建时为其分配值。
代码:我尝试了两种方式:
IEnumerable<RadToolBarButton> collection = ContextMenuColumn.ToList()
.ForEach(x => yield return new RadToolBarButton() { Value = x });
Run Code Online (Sandbox Code Playgroud)
错误 11 无法将类型“void”隐式转换为“System.Collections.Generic.IEnumerable”
IEnumerable<RadToolBarButton> collection =
ContextMenuColumn.SelectMany<string,IEnumerable<RadToolBarButton>>(
x => new RadToolBarButton() { Value = x });
Run Code Online (Sandbox Code Playgroud)
错误 11 无法将类型“Telerik.Web.UI.RadToolBarButton”隐式转换为“System.Collections.Generic.IEnumerable>”。存在显式转换(您是否缺少演员表?)
您应该使用Select而不是ForEach,它可以满足您的需求。
IEnumerable<RadToolBarButton> collection = ContextMenuColumn.ToList()
.Select(x => new RadToolBarButton { Value = x });
Run Code Online (Sandbox Code Playgroud)
我不知道如果内ToList是必要的,你可以逃脱了Cast<T>,而不是物化的中间列表。