0

I'm using the following code which works:

    IEnumerable<Tag> CreateTags()
    {
        var suppliers = SupplierQuery.MatchTerms(Min, Max);

        foreach (var item in suppliers)
        {
            var text = item.Name;
            var route = PageRoute.GetSupplierRoute(item.Name);

            yield return new Tag(text, route);
        }
    }

I've been trying to chain these 2 statments together using a IEnumerable.ForEach extension method, like this:

    IEnumerable<Tag> CreateTags()
    {
        var suppliers = SupplierQuery.MatchTerms(Min, Max)
            .ForEach(x =>
            {
                yield return new Tag(x.Name, PageRoute.GetSupplierRoute(x.Name));

            });
    }

However, I get an error - "Yield statement cannot be used inside an anonymous method" - is there any way round this without creating a new List<Tag> or must they be kept separate?

Thanks in advance.

dotnetnoob
  • 10,783
  • 20
  • 57
  • 103
  • There is no `IEnumerable.ForEach` extension method. You either have a custom extension method that you wrote, or you mean `List.ForEach` – Andrew Whitaker Feb 24 '15 at 14:55

1 Answers1

4

If you insist on using yield return you must use a separate method. In general I'd recommend trying to make due with the existing query operators first. CreateTags can easily be expressed with Select.

In any case ForEach is not equipped to receive a return value from the function that you pass. I think you meant Select.

return SupplierQuery.MatchTerms(Min, Max)
       .Select(x => new Tag(x.Name, PageRoute.GetSupplierRoute(x.Name)));

I think that's all you need.

usr
  • 168,620
  • 35
  • 240
  • 369