How to modify an item in a generic collection before returning to calling code in loop

StackOverflow https://stackoverflow.com/questions/23456088

  •  15-07-2023
  •  | 
  •  

Domanda

Is there a way in the .NET framework to derive from a generic list type such that an operation could be performed on that item before it is returned to the calling code in a foreach loop?

eg - Declaration

public class Items : List<Item> {
    public override Item ?????()
    {
        //do something with item
        return Item;
    }
}

Usage

var items = GetItems();
foreach (var item in items)
{
    // operation declared in Items class has just been executed.
}
È stato utile?

Soluzione

You could implement IList and wrap your list in the implementation.

Override GetEnumerator() and provide a custom enumerator class, which performs your desired operation on item yield.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top