proseidon
proseidon

Reputation: 2305

Can I Linq query into multiple variables?

I'm a bit new to linq and I'm unsure if what I desire is possible. I basically have a class called User that contains a bunch of attributes. I want to only fill in the Name and ID fields that I'm getting from a query. My query gives me the appropriate results, but I am unsure of how to get it into user. This is the closest I get, but I realize it's incorrect.

 IEnumerable<User> UserList;
 UserList = (from o in dbContext.application_user
             join p in dbContext.project on application_user.user_id = project.project_manager
             select o);

This returns a list of User_ID, Firstname, and Lastname, but it doesn't fit into user. My user class has multiple variables, so I was thinking of approaching it by calling 3 IEnumerables, of types int, string, and string, if I could somehow fill all 3 from one query, and then set User = new User(name = x, id = x) etc. Such as

FNameList, LNameList, ID = *insert query here*

Upvotes: 3

Views: 2788

Answers (2)

sloth
sloth

Reputation: 101042

You can just create your instances of User with an Select transformation.

var userQuery = from o in dbContext.application_user
                join p in dbContext.project on application_user.user_id = project.project_manager
                select o;

IEnumerable<User> UserList = from o in userQuery.ToList()
                             select new User() {Name = o.Lastname, ID = o.user_ID};

I don't know how your User class looks like, but you get the idea.

Upvotes: 2

David
David

Reputation: 218818

You can construct the User object inside the Linq query:

IEnumerable<User> UserList;
UserList = (from o in dbContext.application_user
            join p in dbContext.project on application_user.user_id = project.project_manager
            select new User(o.FName, o.LName, o.ID));

This assumes that User has a constructor taking three arguments like those, and that the properties on o are FName, LName, and ID, but you get the idea. The select clause can be used to transform the results into whatever format you need.

Upvotes: 7

Related Questions