Home > Net >  Add list of objects using AddRange alongwith modifying value in each object
Add list of objects using AddRange alongwith modifying value in each object

Time:06-16

I am fetching a list of objects from an api but sometimes one of the elements of each object in that list is fetched as null. If that is the case I want to manually add that element since I have that value.

This is what I have in mind.

var result = List<item>;
foreach(obj in objects)
{
    var items = //api call;
    result.AddRange(items.Select(t => t.Name ?? obj.Name));  //Something like this
}
return result;

I would prefer to use AddRange if possible but I'm open to other solutions.

CodePudding user response:

Try this.

var result = List<item>;
foreach(obj in objects)
{
    var items = //api call;
    var modified = items.Select(t=>{
      t.Name = obj.Name;
      return t; 
    });
    result.AddRange(modified); 
}
return result;
}
  • Related