开发者

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 the开发者_如何学编程re 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 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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜