el-nino
el-nino

Reputation: 399

Add an object to a list within a method, no matter what type they are

i have to add an object to a list. but first, i have to check if that object (the object.name property) does already exist in the list and do some other tests. this all works fine, but i have to do it with different objects and their lists. so what i would like to have is a method, which takes the object and the list as parameters, and does all the magic, no matter of what type the object and the list is.

what i have so far:

the list and the object:

ProductList = new ObservableCollection<Product>();
private Product _newProduct = new Product();
public Product NewProduct
{
    get { return _newProduct; }
    set
    {
        if (_newProduct == value)
            return;
        _newProduct = value;
        RaisePropertyChanged("NewProduct");
    }
}

searching if the object does exist:

bool productFound = false;
for (int i = 0; i < ProductList.Count; i++)
{
    if (ProductList[i].Name == NewProduct.Name)
    {
        productFound = true;
        break;
    }
}

after some other tests, the object is added to the list:

ProductList.Add(NewProduct.Clone());

instead of writing that code for all my lists (5 different types), i would like to call a method and pass the object and the list. the method then performs the tests and adds the object to the list, no matter what type they are. how can i do this?

i am looking for something like this:

Save(NewProduct, ProductList);

Upvotes: 0

Views: 83

Answers (2)

Ahmad
Ahmad

Reputation: 9658

you could use an interface which has the common properties and methods

interface IItem
{
    public string Name {set; get;}
}

then your classes should implement the interface, for example

class Product: Item { ...}

Now you can use the following general method to save the items

public void Save(IItem item, List<IItem> list)
{

    if (!list.Any(x => x.Name == item.Name))
       list.Add(item);
}

Upvotes: 1

Dennis
Dennis

Reputation: 37760

Declare an interface and implement it in all entities you need:

interface INamedEntity : ICloneable
{
    stirng Name { get; }
}

class Product : INamedEntity { /* ... */ }

Then you can re-write code like this:

void Save<T>(List<T> entities, T entity)
    where T: INamedEntity
{
    // searching if the object does exist:
    var isExists = entities.Any(e => e.Name == entity.Name);

    // after some other tests, the object is added to the list:
    entities.Add(entity.Clone());
}

Upvotes: 1

Related Questions