I was making a custom grid that accepts an IEnumerable as an Itemsource. However I was not able to remove an Item inside the itemsource during delete method. 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. 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.
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 ).
Use while loop to traverse the list whilst delete.
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
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; } }
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.