convert a list of objects from one type to another using lambda expression

C#GenericsLambda

C# Problem Overview


I have a foreach loop reading a list of objects of one type and producing a list of objects of a different type. I was told that a lambda expression can achieve the same result.

var origList = List<OrigType>(); // assume populated
var targetList = List<TargetType>(); 

foreach(OrigType a in origList) {
    targetList.Add(new TargetType() {SomeValue = a.SomeValue});
}

Any help would be appreciated- i'm new to lambda and linq thanks, s

C# Solutions


Solution 1 - C#

Try the following

var targetList = origList
  .Select(x => new TargetType() { SomeValue = x.SomeValue })
  .ToList();

This is using a combination of Lambdas and LINQ to achieve the solution. The Select function is a projection style method which will apply the passed in delegate (or lambda in this case) to every value in the original collection. The result will be returned in a new IEnumerable<TargetType>. The .ToList call is an extension method which will convert this IEnumerable<TargetType> into a List<TargetType>.

Solution 2 - C#

If you know you want to convert from List<T1> to List<T2> then List<T>.ConvertAll will be slightly more efficient than Select/ToList because it knows the exact size to start with:

target = orig.ConvertAll(x => new TargetType { SomeValue = x.SomeValue });

In the more general case when you only know about the source as an IEnumerable<T>, using Select/ToList is the way to go. You could also argue that in a world with LINQ, it's more idiomatic to start with... but it's worth at least being aware of the ConvertAll option.

Solution 3 - C#

var target = origList.ConvertAll(x => (TargetType)x);

Solution 4 - C#

List<target> targetList = new List<target>(originalList.Cast<target>());

Solution 5 - C#

I believe something like this should work:

origList.Select(a => new TargetType() { SomeValue = a.SomeValue});

Solution 6 - C#

Here's a simple example..

List<char> c = new List<char>() { 'A', 'B', 'C' };

List<string> s = c.Select(x => x.ToString()).ToList();

Solution 7 - C#

var list1 = new List<Type1>();
var list2 = new List<Type2>();

list1.ForEach(item => list2.Add(new Type2() { Prop1 = value1 }));

Solution 8 - C#

Assume that you have multiple properties you want to convert.

public class OrigType{
    public string Prop1A {get;set;}
    public string Prop1B {get;set;}
}

public class TargetType{
    public string Prop2A {get;set;}
    public string Prop2B {get;set;}
}

var list1 = new List<OrigType>();
var list2 = new List<TargetType>();

list1.ConvertAll(x => new OrigType { Prop2A = x.Prop1A, Prop2B = x.Prop1B })

Solution 9 - C#

Or with a constructor & linq with Select:

public class TargetType {
  public string Prop1 {get;set;}
  public string Prop1 {get;set;}

  // Constructor
  public TargetType(OrigType origType) {
    Prop1 = origType.Prop1;
    Prop2 = origType.Prop2;
  }
}

var origList = new List<OrigType>();
var targetList = origList.Select(s=> new TargetType(s)).ToList();  

The Linq line is more soft! ;-)

Solution 10 - C#

If you need to use a function to cast:

var list1 = new List<Type1>();
var list2 = new List<Type2>();

list2 = list1.ConvertAll(x => myConvertFuntion(x));

Where my custom function is:

private Type2 myConvertFunction(Type1 obj){
   //do something to cast Type1 into Type2
   return new Type2();
}

Solution 11 - C#

for similar type class.

List<targetlist> targetlst= JsonConvert.DeserializeObject<List<targetlist>>(JsonConvert.SerializeObject(<List<baselist>));

Solution 12 - C#

If the types can be directly cast this is the cleanest way to do it:

var target = yourList.ConvertAll(x => (TargetType)x);

If the types can't be directly cast then you can map the properties from the orginal type to the target type.

var target = yourList.ConvertAll(x => new TargetType { SomeValue = x.SomeValue });

Solution 13 - C#

We will consider first List type is String and want to convert it to Integer type of List.

List<String> origList = new ArrayList<>(); // assume populated

Add values in the original List.

origList.add("1");
origList.add("2");
    origList.add("3");
    origList.add("4");
    origList.add("8");

Create target List of Integer Type

List<Integer> targetLambdaList = new ArrayList<Integer>();
targetLambdaList=origList.stream().map(Integer::valueOf).collect(Collectors.toList());

Print List values using forEach:

    targetLambdaList.forEach(System.out::println);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionStrattonView Question on Stackoverflow
Solution 1 - C#JaredParView Answer on Stackoverflow
Solution 2 - C#Jon SkeetView Answer on Stackoverflow
Solution 3 - C#AlpView Answer on Stackoverflow
Solution 4 - C#PranavView Answer on Stackoverflow
Solution 5 - C#Andy WhiteView Answer on Stackoverflow
Solution 6 - C#Ian PView Answer on Stackoverflow
Solution 7 - C#Chris ArnoldView Answer on Stackoverflow
Solution 8 - C#Max ChuView Answer on Stackoverflow
Solution 9 - C#A. MorelView Answer on Stackoverflow
Solution 10 - C#jaimeninoView Answer on Stackoverflow
Solution 11 - C#Arun SolankiView Answer on Stackoverflow
Solution 12 - C#Ayo AdesinaView Answer on Stackoverflow
Solution 13 - C#garima gargView Answer on Stackoverflow