Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

yield return foreach in linq

Problem: Can any one tell me how to return value in linq. I want to return a collection of RadToolBarButtons and assigning them their values at the time of creation.

Code: I tried in two ways:

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

Error 11 Cannot implicitly convert type 'void' to 'System.Collections.Generic.IEnumerable'

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

Error 11 Cannot implicitly convert type 'Telerik.Web.UI.RadToolBarButton' to 'System.Collections.Generic.IEnumerable>'. An explicit conversion exists (are you missing a cast?)

like image 735
Wajahat Avatar asked Oct 26 '25 05:10

Wajahat


2 Answers

You should use Select instead of ForEach, it does what you are looking for.

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

I am not sure if the inner ToList is necessary, you may be able to get away with a Cast<T> instead of materializing the intermediate list.

like image 182
Sergey Kalinichenko Avatar answered Oct 29 '25 08:10

Sergey Kalinichenko


Use Select instead of ForEach, it will do the yield return for you

like image 39
Julien Ch. Avatar answered Oct 29 '25 10:10

Julien Ch.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!