Is it somehow possible to transform an entire collection instead of doing them one by one?
I am often in a situation where I need to convert elements in a list from one type to another type. The solution i usually end up with is something like this
using System;
using System.Collections.Generic;
using System.Linq;
namespace ListProcessing
{
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
public string Department { get; set; }
}
public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
public string Position { get; set; }
}
class Program
{
public static List<Employee> Hire(List<Person> persons)
{
var output = new List<Employee>();
foreach(var p in persons)
{
var employee = new Employee { Id = p.Id, Name = p.Name, Position = "Software Engineer" };
}
return output;
}
static void Main(string[] args)
{
List<Person> persons = new List<Person>
{
new Person { Id = 1, Name = "John Doe", Department = "Software" },
new Person { Id = 2, Name = "Jane Smith", Department = "Marketing" },
new Person { Id = 3, Name = "Bob Johnson", Department = "Software" },
new Person { Id = 4, Name = "Sally Jones", Department = "HR" }
};
//Attempt 1
IEnumerable<Employee> employees = persons
.Select(p => new Employee { Id = p.Id, Name = p.Name, Position = "Software Engineer" });
//Attempt 2
var employees2 = Hire(persons);
foreach (Employee employee in employees)
{
Console.WriteLine($"ID: {employee.Id}, Name: {employee.Name}, Position: {employee.Position}");
}
}
}
}
Either doing it by linq or by inserting each element into a list and returning them.
Some sort of iteration is always needed, and the fact the same instruction has to be done foreach item is what annoys me..
I sort of feel like this could be solved either using the right type from the beginning, or some sort of overload mechanism could be implmented that does not iterate them, but basically process the collection as a collection and returns the same collection "processed" - and O(1) operation.
Converting a list with N elements is a O(N) operation and there is no way to make it a O(1) operation. A list of a reference type is not a monolith. It is storing references to objects that live somewhere else. However, your design could be improved.
You can make an inheritance hierarchy like this:
Note that because the
Personclass is abstract, you cannot instantiate it; however, you can declare aList<Person>and add it objects of the the two derived classes.If the employees should have a department as well, then change the hierarchy to this (
Personis not abstract here):I also added a copy constructor to
Employeeto ease the transformation of a Person to an Employee.But since Persons and Employees are individual objects, it is not possible to convert them all at once. This is simply not possible. But don't over-estimate the time this takes. You can transform one million persons like this and won't notice any lag.