1
votes

Hi I am trying to use Lambda Expression to cast anonymous type list to primitive type list, so far I have no luck.

I know I can use foreach to loop through 'a' and get the values, but I want to know how to do it in Lambda or Linq.

var a = new []{ new {name= "jerry", age = 32}, new {name="peter",age=23}};

List<string> b = a.Select(p => new System.String{p.name}).ToList();
List<int> c = a.Select(p => new System.Int32{p.age}).ToList();
3
I thought we always need to cast it to an object. Thanks guys for your answers. - Jerry Liang

3 Answers

2
votes
        var a = new[] { new { name = "jerry", age = 32 }, new { name = "peter", age = 23 } };

        List<string> b = a.Select(p => p.name).ToList();
        List<int> c = a.Select(p => p.age).ToList(); 

The problem is with your use of { and } in new System.String{p.name}. That isn't a valid way to instantiate a type.

2
votes
var a = new[] { new { name = "jerry", age = 32 },new {name = "peter", age = 23}};

List<string> b = a.Select(p => p.name).ToList();
List<int> c = a.Select(p => p.age).ToList();
2
votes

Why do you try to instantiate a new instance by calling constructors?

this:

var a = new []{ new {name= "jerry", age = 32}, new {name="peter",age=23}}; 

List<string> b = a.Select(p => p.name}).ToList(); 
List<int> c = a.Select(p => p.age).ToList(); 

works fine. p.Age is an integer and therefore a value type. That means that it's copied by value so you do get a unique copy in your list c. p.name is a string. In .NET strings are immutable so it's perfectly save to share the instance of a string.

Note also that both constructs dont even exist! Another note is that when calling a constructor, you need to use () not { }