Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do i convert from one collection to another

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

like image 862
leora Avatar asked Dec 07 '22 01:12

leora


2 Answers

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...
                });
like image 146
Reed Copsey Avatar answered Dec 09 '22 14:12

Reed Copsey


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.

like image 28
Ruben Bartelink Avatar answered Dec 09 '22 13:12

Ruben Bartelink