Home > other >  How can I add an item to a IEnumerable<(T item, int? number)>?
How can I add an item to a IEnumerable<(T item, int? number)>?

Time:05-30

So, I have method:

public static IEnumerable<(T item, int? number)> DoTheThing<T>(this IEnumerable<T> enumerable, int? someNumber)

Basically I need return collection from parameters with added numbers in some cases. I created empty collection to store data while forming end result trough foreach:

IEnumerable<(T item, int? number)> enumResult = Enumerable.Empty<(T item, int? number)>();

But I can't figure out how to add values to enumResult. Only thing I can't change - method signature, so maybe I'm doing wrong thing entirly.

CodePudding user response:

The point of the interface is that you don't need to know anything about the source of the list, only that you can enumerate it. It could be that the method returns a list, computes the elements on the fly or reads them from the internet one at a time.

To add a value, you'll need to make sure that you work with a List<T>:

var enumResult = new List<(T item, int? number)>();
enumResult.Add(...);

Note that a List is also an IEnumerable so you can still use enumResult wherever the IEnumerable is expected.

CodePudding user response:

how about

      public static IEnumerable<(T item, int? number)> DoTheThing<T>(this IEnumerable<T> enumerable, int? someNumber){
        foreach (T val in this){
          yield return val; 
        }
        if(someNumber.HasValue)
           yield return someNumber.Value;
      }
  • Related