c#:如何删除IEnumerable中的Item

我正在制作一个自定义网格,它接受一个I​​Enumerable作为Itemsource。 但是我在删除方法期间无法删除itemsource中的Item。 你们能帮我使用下面的代码吗?

static void Main(string[] args) { List source = new List(); int itemsCount = 20; for (int i = 0; i < itemsCount; i++) { source.Add(new MyData() { Data = "mydata" + i }); } IEnumerable mItemsource = source; //Remove Sample of an mItemSource //goes here .. } public class MyData { public string Data { get; set; } } 

你不能。 IEnumerable (和它的通用对应物IEnumerable )仅用于 – 枚举某些集合的内容。 它没有提供修改集合的工具。

如果您正在寻找提供修改集合的所有典型方法的接口(例如,添加,删除),那么如果您需要按索引访问元素,请查看ICollectionIList

或者,如果您的目标是为某些内容提供IEnumerable ,但删除了一些项目,请考虑使用Enumerable.Except()将其过滤掉( 因为它是枚举的 )。

在删除时使用while循环遍历列表。

 int i = 0; while(i < source.Count){ if(canBeRemoved(source[i])){ source.RemoveAt(i); }else{ i++; } } 

我能够使用动态从Itemsource中删除Item

  static void Main(string[] args) { List source = new List(); int itemsCount = 20; for (int i = 0; i < itemsCount; i++) { source.Add(new MyData() { Data = "mydata" + i }); } IEnumerable mItemsource = source; //Remove Sample of an mItemSource dynamic d = mItemsource; d.RemoveAt(0); //check data string s = source[0].Data; } public class MyData { public string Data { get; set; } }