如何在IEnumerable中设置属性

时间:2019-06-12 23:38:36

标签: c#

我想更改IEnumerable中的属性的值,但不会更改。

IEnumerable<T1> enumlist = null;
IList<T1> personList = SelectAll();

enumlist = personList.Where(p => p.propertyA.Contains(searchText));

for (int i = 0; i < enumlist.Count(); i++)
{
     enumlist .ElementAt(i).PrpertyA = "blah blah...";
}

1 个答案:

答案 0 :(得分:-1)

您不能在可能尚未实现的状态下进行迭代。这是它的工作原理

IEnumerable.GetEnumerator()返回一个 enumerator 对象(实现IEnumerator)。它具有返回当前项目的属性Current和方法MoveNext(),该方法将枚举数前进到下一个项目。

该接口不能保证已被枚举,并且不会公开索引器。为了能够访问可以枚举的内容的索引,需要以特定的方式对其进行访问。像foreach循环,或直接使用IEnumerbale接口,或通过已经完成并将其转换为支持直接索引的方法的方法

选项1

// create a concrete List out of the Enumerbale
var list = personList.Where(p => p.propertyA.Contains(searchText)).ToList();

for (int i = 0; i < enumlist.Count(); i++)
   enumlist[i].PrpertyA = "blah blah...";

选项2

enumlist = personList.Where(p => p.propertyA.Contains(searchText));

// Use the iterative properties of foreach to enumerate enumlist 
foreach(var item in enumlist)
    item.PrpertyA = "blah blah...";
相关问题