Link to home
Start Free TrialLog in
Avatar of deleyd
deleydFlag for United States of America

asked on

Is ConvertAll necessary?

I have a List<A> listA a list of objects of type A. I want to make a new list. Is there any difference between the following:
given: List<A> listA
var List<A> newListA = new List<A>(listA);
var List<A> newListA = new List<A>(listA.ConvertAll((x) => (A)x));

Open in new window

I'm trying to figure out why some old code has this .ConvertAll in it and if it's necessary.
Avatar of it_saige
it_saige
Flag of United States of America image

There is no difference between the two as presented.  Proof of concept -
using System;
using System.Collections.Generic;
using System.Linq;

namespace EE_Q29160843
{
	class Program
	{
		static void Main(string[] args)
		{
			var initial = (from i in Enumerable.Range(0, 20) select new A { Index = i, Name = $"Name{i}" }).ToList();
			var copied = new List<A>(initial);
			var converted = new List<A>(initial.ConvertAll(x => (A)x));
			Console.WriteLine($"Sequence copied Equals converted? {copied.SequenceEqual(converted)}");
			Console.ReadLine();
		}
	}

	class A
	{
		public int Index { get; set; }
		public string Name { get; set; }

		public override string ToString()
		{
			return $"{{ Index: {Index}, Name: {Name} }}";
		}
	}
}

Open in new window

Results in the following output -User generated image-saige-
ASKER CERTIFIED SOLUTION
Avatar of Eduard Ghergu
Eduard Ghergu
Flag of Romania image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial