'Copy list B to list A when A and B contain the same fields
I saw a method that copies the fields between two different objects but with identical fields.
The question is there a way to copy a list of A to a list of B?
public class A
{
public int X { get; set; }
public int Y { get; set; }
}
public class B
{
public int X { get; set; }
public int Y { get; set; }
}
public Main()
{
B b = new B { X = 10, Y = 2 };
A a = new A();
CopyProperties(b, a); // it works
List<B> listB = new List<B> { new B { X = 5, Y = 4 } };
List<A> listA = new List<A>();
CopyProperties(listB, listA); // it doesn't work
}
public static Target CopyProperties<Source, Target>(Source source, Target target)
{
foreach (var sProp in source.GetType().GetProperties())
{
bool isMatched = target.GetType().GetProperties().Any(tProp => tProp.Name == sProp.Name && tProp.GetType() == sProp.GetType() && tProp.CanWrite);
if (isMatched)
{
var value = sProp.GetValue(source);
PropertyInfo propertyInfo = target.GetType().GetProperty(sProp.Name);
propertyInfo.SetValue(target, value);
}
}
return target;
}
Solution 1:[1]
You could use LINQ:
List<B> listB = new List<B> { new B { X = 5, Y = 4 } };
List<A> listA = listB.Select(x => CopyProperties(x, new A()).ToList();
This iterates listB, creates a new instance of A for each entry of the list, copies the entry of listB into the newly created instance and stores them in a new list.
Online demo: https://dotnetfiddle.net/rfL3fn
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | SomeBody |
