Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update a specific column of a List <T>

Tags:

c#

.net

asp.net

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!

like image 624
Jonathan Burgos Gio Avatar asked Nov 23 '17 15:11

Jonathan Burgos Gio


2 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;
        });
    }           
}
like image 128
Kevin Wallis Avatar answered Oct 11 '22 14:10

Kevin Wallis


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);
like image 32
DavidG Avatar answered Oct 11 '22 15:10

DavidG