开发者

Convert IEnumerable<X> to List<Y>

开发者 https://www.devze.com 2023-01-23 10:12 出处:网络
i have, (in Linq), an IEnumerable of type Client. Now i have to return a Generic List of type ClientVM.

i have, (in Linq), an IEnumerable of type Client. Now i have to return a Generic List of type ClientVM. ClientVM is a subset of Client (not a subtype or anything), and i can't get it to work.

Below is the code i have so far, but it doesn't work this way.开发者_运维技巧 But maybe this code can give you an addition to my post to specify what i want to do:

clientVMs = clients.ToList().ConvertAll(new ClientVM( z => z.Reference, z=>z.Fullname ));

clientVMs is a generic List<ClientVM>, class ClientWM has a constructor that takes the two properties, clients is the IEnumerable<Client>

And, offtopic, the compiler messages when you're dealing with Generics aren't readible for humans, imho.


Maybe something like this?

var clientVMs = clients.Select(c => new ClientVM(c.Reference, c.Fullname))
                       .ToList();


You've got the wrong syntax for the delegate inside ConvertAll:

clientVMs = clients.ToList().ConvertAll(z => new ClientVM( z.Reference, z.Fullname ));


Your lambda expressions are misplaced. You probably want:

var clientVMs = clients.ToList().ConvertAll(
    client => new ClientVM(client.Reference, client.Fullname));


clients.ToList().Select(new ClientVM{ z => z.Reference, z=>z.Fullname }).ToList();
0

精彩评论

暂无评论...
验证码 换一张
取 消