Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting IQueryable<T> object to another object?

Tags:

c#

.net

I have no idea what the keywords are so here is an example of what I want:

return from i in userRepo.GetUsers()
  select new SimpleUser{
        i.UserId,
        i.Name
  };

userRepo.GetUsers() returns type IQueryable<User>. I'd like to convert this to IQueryable<SimpleUser> to I can restrict access to certain properties of the User domain.

How do I do this without hard coding the translation like this? What about tools like automapper or ValueInjecter, how can they do this?

Also, what is this technique called?

like image 894
Shawn Mclean Avatar asked Apr 02 '11 14:04

Shawn Mclean


2 Answers

Provided that SimpleUser is assigneable to User (User is an interface of baseclass of SimpleUser), you can

 var users = simpleUsers.Cast<User>();

optionally with

 var users = simpleUsers.Cast<User>().AsQueryable();

And if you're not sure whether all items are actually Users, then you can use OfType<User> instead of Cast<User>

like image 193
sehe Avatar answered Oct 18 '22 16:10

sehe


This question is 9 years old so idk if it existed then but for anyone searching now, using .FirstOrDefault() works if you pick a single user.

like image 31
Moataz Alsayed Avatar answered Oct 18 '22 16:10

Moataz Alsayed