i have:
IEnumerable<Foo> foolist
and i want to convert this to:
IEnumerable<Bar> barlist
is there a linq / lambda solution to move from one to the other
both objects (foo and bar) have simple properties that i am going to convert. for example:
bar.MyYear = foo.Year
they each have about 6 properties
You can do:
IEnumerable<Bar> barlist = foolist.Select(
foo => new Bar(foo.Year)); // Add other construction requirements here...
Enumerable.Select is really a projection function, so it is perfect for type conversions. From the help:
Projects each element of a sequence into a new form.
Edit:
Since Bar
doesn't have a constructor (from your comments), you can use object initializers instead:
IEnumerable<Bar> barlist = foolist.Select(
foo => new Bar()
{
Year = foo.Year,
Month = foo.Month
// Add all other properties needed here...
});
In terms of general data processing patterns, the map of the general Map/Reduce paradigm is the underlying principle we're looking for (which maps, if you'll pardon the pun, to Select
in LINQ, as @Reed Copsey gives a good example of)
AutoMapper is a library which implements such convention based projection/mapping in environments where LINQ would apply and may be worth investigating for you if you have a sufficiently complex set of requirements to warrant introducing the cognitive overhead of bring another library to the party in your context.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With