plutomusang
plutomusang

Reputation: 59

c#: how do I remove an Item inside IEnumerable

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; } }

Upvotes: 0

Views: 10170

Answers (3)

Jonathon Reinhart
Jonathon Reinhart

Reputation: 137557

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).

Upvotes: 7

Bryan
Bryan

Reputation: 1

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; } }

Upvotes: -2

Shao Jun
Shao Jun

Reputation: 31

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++;    
    }
}

Upvotes: -2

Related Questions