leora
leora

Reputation: 196589

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

Upvotes: 4

Views: 4899

Answers (3)

jnielsen
jnielsen

Reputation: 202

If there is a reference (or identity) conversion between Foo and Bar, then this is an example of covariance or contravariance in generics.

C#4.0 supports covariance and contravariance in generics.

The code should look something like:

IEnumerable<Foo> foolist = new List<Foo>();

IEnumerable<Bar> barlist = foolist;

If you are < C#4.0 then Reed's answer is your baby.

More on this can be found at:

http://msdn.microsoft.com/library/dd799517(VS.100).aspx

Upvotes: 1

Ruben Bartelink
Ruben Bartelink

Reputation: 61815

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.

Upvotes: 1

Reed Copsey
Reed Copsey

Reputation: 564461

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...
                });

Upvotes: 13

Related Questions