How to 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 for moving from one to another

Both objects (foo and bar) have simple properties that I'm going to convert. eg:

 bar.MyYear = foo.Year

each of them has about 6 properties

+3
source share
3 answers

You can do:

IEnumerable<Bar> barlist = foolist.Select(
         foo => new Bar(foo.Year)); // Add other construction requirements here...

Enumerable.Select is a truly projective function, which is why it is ideal for type conversion. Via:

Projects each element of a sequence into a new form.


Edit:

Since it Bardoes not 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...
                });
+6

Map/Reduce , ( , , Select LINQ, @ )

AutoMapper - , , LINQ , , , , .

+1

( ) Foo Bar, generics.

# 4.0 .

:

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

IEnumerable < > barlist = foolist;

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

You can learn more about this at:

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

+1
source

Source: https://habr.com/ru/post/1768537/


All Articles