Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update list by another list (linq)

Tags:

c#

linq

I have List of object of class "Data" that look like:

class Data
{
    int code;
    string name;
    ...
    DateTime date_update;
}

and I have another list of class, like:

class RefCodes
{
    int old_code;
    int new_code;
    string new_name;
    DateTime date_update;
}

The list of "Data" contains like 1,000 objects. The list of "RefCodes" contains like 30 objects.

I need to replace in list "Data", the fields: "code" to be with value of "new_code", and the "name" to be with value of "new_name".

The replacement need to be only for the objects that their code exist in list "RefCodes". by the query: if code in Data.code == RefCodes.old_code How can I do it?

like image 412
prog_prog Avatar asked Dec 23 '22 21:12

prog_prog


2 Answers

I think you're looking for this:

foreach (var rcodeObj in RefCode)
{
     foreach(var obj in (Data.Where(t => t.code == rcodeObj.old_code)))
     {
        obj.code = rcodeObj.new_code;
        obj.name = rcodeObj.new_name;
     }
}
like image 123
CDove Avatar answered Dec 28 '22 06:12

CDove


If you are using C#6 you could use linq to do something like this

var updatedData = data.Select(x => new Data
{
   code = refCodes.FirstOrDefault(y => y.old_code == x.code)?.new_code ?? x.code,
   name = refCodes.FirstOrDefault(y => y.old_code == x.code)?.new_name ?? x.name,
});
like image 41
Bad Dub Avatar answered Dec 28 '22 05:12

Bad Dub