Domanda

I would like to invoke a method when into my List property were added specific count of items. Actually I need to find way how to automatically check if a Collection has given count of items and after that call a method.

Ok, one example. I have a class MyClass

public class MyClass
{
    public List<string> Url { get; set; }

    public void fullList()
    {
        //some work with the List
    }
}

And now somewhere in main function I create instance of MyClass and add some items.

MyClass mc = new MyClass();
mc.Url = new List<string>();
mc.Url.Add("www.1.com");
mc.Url.Add("www.2.com");
//now on 3rd added item I want to invoke method fullList from class MyClass
mc.Url.Add("www.3.com");
È stato utile?

Soluzione

You should probably create have a class that encapsulates the URL list and the behavior you want. I guess the behavior is that the list gets "full" when it hits 3 items and then you want an event to be raised that MyClass can listen on.

class MyUrls 
{
    List<string> _urls = new List<string>();

    public void Add(string url)
    {
        _urls.Add(url);
        if (_urls.Count == 3 && OnFull != null)
            OnFull.Invoke();
    }

    public IEnumerable<string> Urls
    {
        get
        {
            return _urls;
        }
    }

    public event Action OnFull;
}

and use it like this:

public class MyClass
{
    public MyClass()
    {
       Urls.OnFull += fullList;
    }
    public MyUrls Urls { get; }

    public void fullList()
    {
        //some work with the List
    }
}

MyClass mc = new MyClass();
mc.Urls = new List<string>();
mc.Urls.Add("www.1.com");
mc.Urls.Add("www.2.com");
//now on 3rd added item I want to invoke method fullList from class MyClass
mc.Urls.Add("www.3.com");

Altri suggerimenti

Don't reinvent the wheel - use the ObservableCollection<T>.

You can attach a handler to the CollectionChanged event that gets called when the collection is modified.

ObservableCollection<string> collection = new ObservableCollection<string>();

collection.CollectionChanged += (sender, args) => {
    if(args.Action == NotifyCollectionChangedAction.Add &&
        collection.Count == 3)
        HandleItemsAdded(args.NewItems.Cast<string>());         
};

collection.Add("www.1.com");
collection.Add("www.2.com");
collection.Add("www.3.com");

Handler:

public static void HandleItemsAdded(IEnumerable<string> newItems)
{
    foreach(var item in newItems)
        Console.WriteLine(item);
}

Working Fiddle: http://dotnetfiddle.net/eIeilP

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top