I've got a Dictionary
that contains a ValueTuple
:
private static readonly Dictionary<RELAY, (byte RelayNumber, bool IsClosed)> s_relays = new Dictionary<RELAY, (byte RelayNumber, bool IsClosed)>
{
{ RELAY.OUTPUT1, (4, false) },
{ RELAY.OUTPUT2, (9, false) },
{ RELAY.OUTPUT3, (11, false) },
};
Later in my code I set IsClosed
to true for one or more relays. I wrote a ForEach
extension method for the Dictionary
:
public static IEnumerable<T> ForEach<T>(this IEnumerable<T> enumeration, Action<T> action)
{
Debug.Assert(enumeration != null, $"Argument {nameof(enumeration)} cannot be null!");
Debug.Assert(action != null, $"Argument {nameof(action)} cannot be null!");
foreach (T item in enumeration)
{
action(item);
yield return item;
}
}
I want to call a method for each relay that is closed. For example, writing to Console.WriteLine
:
Relays.Where(x => x.Value.IsClosed).ForEach(x => Console.WriteLine(x.Key));
But this does not work. However, if I include ToList()
the code below does work:
Relays.Where(x => x.Value.IsClosed).ToList().ForEach(x => Console.WriteLine(x.Key));
What am I missing?
(I do realize that the ForEach
extension method being called is different between these two examples with the first one [mine] never being called.)