AnIEnumerable
只能用于读取集合,但不能对其进行更改。如果要对其进行更改,请改为返回过滤索引的枚举。
public IEnumerable<int> FilteredIndexes
{
get
{
if (UsePredicate) {
return ItemsList
.Select((item, i) => i)
.Where(i => SomeCondition(ItemsList[i]));
}
return ItemsList.Select((item, i) => i);
}
}
假设你已经声明了这个索引器
public T this[int index]
{
get { return ItemsList[index]; }
set { ItemsList[index] = value; }
}
您现在可以像这样使用该集合
GenClass<string> stringCollection = new GenClass<string>();
//TODO: Add items
stringCollection.SomeCondition = s => s.StartsWith("A");
stringCollection.UsePredicate = true;
foreach (int index in stringCollection.FilteredIndexes) {
stringCollection[index] = stringCollection[index] + " starts with 'A'";
}
更新
如果您不想公开索引,则可以创建一个用作表示您的集合项目的项目访问器的类
public class Item<T>
{
private List<T> _items;
private int _index;
public Item(List<T> items, int index)
{
_items = items;
_index = index;
}
public T Value
{
get { return _items[_index]; }
set { _items[_index] = value; }
}
}
在您的收藏中,您将声明此属性
public IEnumerable<Item<T>> FilteredItems
{
get
{
if (UsePredicate) {
return ItemsList
.Select((item, i) => new Item<T>(ItemsList, i))
.Where(item => SomeCondition(item.Value));
}
return ItemsList.Select((item, i) => new Item<T>(ItemsList, i));
}
}
现在你可以像这样使用集合了
foreach (Item<string> item in stringCollection.FilteredItems) {
item.Value = item.Value + " starts with 'A'";
}
一般注意事项:您可以安全地将私有属性转换为字段。属性通常用作公开公开字段值的中间体。