Update a specific column of a List <T>

Viewed 5410

First they forgive me for my English since it is not my native language. I have a method which receives a generic list List<T>. what I want is to foreach through the whole list and be able to update a column called Eliminated of each class T and which is of the boolean type, is it possible to do? can anybody help me.

This is what I have so far:

// Delete (Change status delete = true)
public void Delete<T>(List<T> data)
{      
    if (data != null)
    {
        data.ForEach(x =>
        {
           ...
        });
    }           
}

Thanks in advance!

3 Answers

Instead of T i would use an interface, because otherwise in the foreach you cannot access the property Eliminated.

Here the interface:

interface IExample {

    bool IsEliminated { get; set; }    

}

and here the method with the ForEach loop.

public void Delete<T>(List<T> data) where T : IExample
{      
    if (data != null)
    {
        data.ForEach(x =>
        {
           x.Eliminated = true;
        });
    }           
}

If you want a generic method to update a list of any type, you could do something like this:

public void Update<T>(List<T> data, Action<T> func)
{
    if (data == null)
        throw new ArgumentNullException(nameof(data));

    data.ForEach(func);
}

Note I've change the null check to throw if you pass in a null list. You could just return here instead, this way eliminates some nesting.

This allows you to pass in an action that you apply to every item in a collection. You would use it like this:

var data = new List<YourClass> = GetData();

Update(data, item => item.Eliminated = true);

Your T has no property called Eliminated. Your compiler cannot guarantee that any T you will ever use with this method will have that member, so you are not allowed to compile it that way.

You could put a constraint on your T that allows the compiler to make sure the property exists:

public interface Eliminatable
{
    bool Eliminated { get; set; }
}

public void Delete<T>(List<T> data) where T : Eliminatable
{      
    if (data != null)
    {
        data.ForEach(x => { x.Eliminated = true; });
    }           
}

Or (and some may say this is a hack) you can just trust your users that they will in fact pass something as T that confirms to your pattern:

public void Delete<T>(List<T> data)
{      
    if (data != null)
    {
        data.ForEach(x => { dynamic d = x; d.Eliminated = true; });
    }           
}

Now this will fail if the property is not there. At runtime. Not nice. But it "works".

Related