Mous Kamel Mous Kamel - 3 years ago 191
ASP.NET (C#) Question

Implement Update() method in a class derived from List(T) Class (System.Collections.Generic)

I would like to be able to update a list by calling a method in my PersistentList instance.

public class PersistentList<T> : List<T> where T : class, new()
{
public void Update(T Item){//...}
}


so Instead of :

public ActionResult Edit(Article a)
{
if (ModelState.IsValid)
{
Article old = la.Find(p => p.Id == a.Id);
int index = pl.IndexOf(old);
pl[index] = a;
pl.SaveChanges();
return this.RedirectToAction("Index", "Home");
}
else { return View(); }
}


I want something like

public ActionResult Edit(Article a)
{
if (ModelState.IsValid)
{
pl.Update(a); //I'll call SaveChanges() in it.
return this.RedirectToAction("Index", "Home");
}
else { return View(); }
}


I'm a little lost. Any tips would be nice! Thank you

This is what I tried so far :

public void Update(T item)
{
T old = base.Find(p => p.GetHashCode() == item.GetHashCode());
int index = base.IndexOf(old);
base[index] = item;
SaveChanges();
}

Answer Source

Create an interface for your items to derive from containing the Id property:

public interface IItem
{
    int Id { get; set; }
}

And have another generic constraint for your list on it:

public class PersistentList<T> : List<T> where T : class, new(), IItem
{
    public void Update(T item)
    {
        // T must derive from the interface by constraint
        T old = base.Find(p => p.Id == item.Id);
        int index = base.IndexOf(old);
        base[index] = item;
        SaveChanges();
    }
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download