[英]c#: how do I remove an Item inside IEnumerable
I was making a custom grid that accepts an IEnumerable as an Itemsource. 我正在制作一个接受IEnumerable作为Itemsource的自定义网格。 However I was not able to remove an Item inside the itemsource during delete method. 但是,在删除方法期间,我无法删除itemsource中的一个Item。 Will you guys be able to help me using the code below? 你们可以使用下面的代码来帮助我吗?
static void Main(string[] args)
{
List<MyData> source = new List<MyData>();
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; } }
You can't. 你不能 IEnumerable
(and its generic counterpart IEnumerable<T>
) is for just that - enumerating over the contents of some collection. IEnumerable
(及其通用的IEnumerable<T>
)仅用IEnumerable<T>
目的-枚举某些集合的内容。 It provides no facilities for modifying the collection. 它不提供修改集合的功能。
If you are looking for an interface that provides all the typical means of modifying a collection (eg. Add, Remove) then have a look at ICollection<T>
or IList<T>
if you need to access elements by index. 如果您正在寻找一个提供所有典型方法来修改集合的接口(例如,添加,删除),那么如果需要按索引访问元素,请查看ICollection<T>
或IList<T>
。
Or, if your goal is to provide an IEnumerable
to something, but with some items removed, consider Enumerable.Except()
to filter them out ( as it is enumerated ). 或者,如果您的目标是为某些内容提供IEnumerable
,但删除了某些项目,请考虑使用Enumerable.Except()
过滤掉它们( 如枚举 )。
Use while loop to traverse the list whilst delete. 使用while循环在删除时遍历列表。
int i = 0;
while(i < source.Count){
if(canBeRemoved(source[i])){
source.RemoveAt(i);
}else{
i++;
}
}
I was able to remove Item from the Itemsource using dynamic 我能够使用动态从Itemsource中删除Item
static void Main(string[] args)
{
List<MyData> source = new List<MyData>();
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; } }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.