C #: how to remove an element inside IEnumerable

I created a custom grid that accepts IEnumerable as an Itemource. However, I could not delete the item inside the items source during the delete method. Will you guys 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; } } 
0
source share
3 answers

You can not. IEnumerable (and its general counterpart IEnumerable<T> ) for this is an enumeration of the contents of some collection. It does not provide an opportunity to modify the collection.

If you are looking for an interface that provides all the typical tools for modifying a collection (for example, Add, Remove), see ICollection<T> or IList<T> if you need to access elements by index.

Or, if your goal is to provide IEnumerable to something, but if some elements are removed, consider Enumerable.Except() to filter them (as listed).

+7
source

Use while to traverse the list during deletion.

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

I was able to remove an item from Itemource 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; } } 
-2
source

Source: https://habr.com/ru/post/1436769/


All Articles