3

I have objects from ClassA and want to use them to create objects of ClassB. I know how to do that if I'm just dealing with one object at a time:

ClassA object1 = new ClassA();
ClassB object2 = new ClassB(object1);

class ClassA
{
    public DateTime Timestamp;
    public double X;
    public double Y;
    public double Z;

    public ClassA()
    {
       // other stuff
    }
}

class ClassB
{
    public DateTime Timestamp;
    public double X;

    public ClassB(ClassA A)
    {
        Timestamp = A.Timestamp;
        X = A.X;
    }
}

However, I'm looking for the best way to do it with lists of objects. I want to take the list of type ClassA, and create a list of type ClassB:

List<ClassA> list_of_classA = new List<ClassA>();
List<ClassB> list_of_classB = ????
1
  • 4
    Assuming the same constructors, can you just list_of_classA.Select(classA => new ClassB(classA)).ToList()?
    – Scott
    Jul 13, 2017 at 20:13

4 Answers 4

5

In addition to the query style syntax that Markus has demonstrated, you can use lambda style syntax to project your list of ClassA to ClassB

var listOfClassB = list_of_classA.Select(x => new ClassB(x)).ToList()
1
  • Worked great. Reading up on lambda style syntax now. Thanks
    – MikeD
    Jul 15, 2017 at 6:28
3

You can use Linq to project the list to a new list of type ClassB:

List<ClassB> list_of_classB = (from x 
                               in list_of_classA
                               select new ClassB(x)).ToList();

To start, you can find a lot of good samples on Linq here.

2

Just to throw in a 3rd way to do this:

List<ClassA> list_of_classA = new List<ClassA>();
List<ClassB> list_of_classB = new List<ClassB>();

foreach (ClassA item in list_of_classA)
        {
            list_of_classB.Add(new ClassB(item));
        }

This will accomplish the same thing without using Linq or Lambda expressions. If possible, you would most likely want to use one of the other 2 answers provided. However if you are unfamiliar with Linq or Lambda expressions then this may be helpful.

1
  • Thanks. For my purposes this worked fine and was just as fast as the other methods according to System.Diagnostics.Stopwatch
    – MikeD
    Jul 15, 2017 at 6:26
2

You most likely want to use Select as others have suggested

That said, if the only thing you want to do is to do conversions of lists and performance is very important then List has a method called ConvertAll that you could use.

List<ClassA> list_of_classA = new List<ClassA>();
List<ClassB> list_of_classB = list_of_classA.ConvertAll((ClassA a) => new ClassB(a));

You can read more about the differences between using Select and ConvertAll here with regards to performance and here with regards to their differences otherwise.

Since ConvertAll is the less generic one (only works for Lists) it should be faster than the Select option that is more generic. I tried to disprove this idea by doing a few tests.

I created a list with 5 and 10 million objects in the A-list and tested the ConvertAll and Select options and got these results:

enter image description here enter image description here

Where the y-axis is in ms.

So the data seems to suggest that ConvertAll is, in fact, a bit faster. However, my code might have some issues that cause these differences so take this with a grain of salt.

Here is the code I used. Compiled for release to x64. (also modified ListA so that it actually had a proper constructor)

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;

namespace lekstuga
{
    class Program
    {
        static void Main(string[] args)
        {
            int loops = 10000000;

            for (var n = 0; n < 4; n++)
            {

                Stopwatch stopwatch;

                List<ClassA> listOfClassA2 = new List<ClassA>();
                List<ClassB> listOfClassB2 = new List<ClassB>();

                for (int i = 0; i < loops; i++)
                {
                    listOfClassA2.Add(new ClassA(DateTime.Now, 1, 2, 3));
                }

                stopwatch = Stopwatch.StartNew(); //creates and start the instance of Stopwatch
                listOfClassB2 = listOfClassA2.ConvertAll((ClassA a) => new ClassB(a));
                stopwatch.Stop();

                Console.WriteLine("ConvertAll " + stopwatch.ElapsedMilliseconds + "ms");


                List<ClassA> listOfClassA = new List<ClassA>();
                List<ClassB> listOfClassB = new List<ClassB>();

                for (int i = 0; i < loops; i++)
                {
                    listOfClassA.Add(new ClassA(DateTime.Now, 1, 2, 3));
                }

                stopwatch = Stopwatch.StartNew(); //creates and start the instance of Stopwatch
                listOfClassB = listOfClassA.Select(x => new ClassB(x)).ToList();
                stopwatch.Stop();

                Console.WriteLine("Select " + stopwatch.ElapsedMilliseconds + "ms");
            }
            Console.ReadLine();
        }

        class ClassA
        {
            public DateTime Timestamp;
            public double X;
            public double Y;
            public double Z;

            public ClassA(DateTime t, double x, double y, double z)
            {
                Timestamp = t;
                X = x;
                Y = y;
                Z = z;
            }
        }

        class ClassB
        {
            public DateTime Timestamp;
            public double X;

            public ClassB(ClassA A)
            {
                Timestamp = A.Timestamp;
                X = A.X;
            }
        }
    }
}

Finally, a note on Select, while it is lazy and does not execute before actually needed the use of .ToList() forces LINQ to calculate the data right away so Select and ConvertAll are comparable in this respect.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.