Brisbe
Brisbe

Reputation: 1618

How do I pull a single column from a c# list?

My code defines an LoginUser object, with a number of columns -- LoginUserId, UserName, ActiveFlag, etc. I have a List<LoginUser> of these objects.

Right now, my code creates a List<int>, then iterates through the List<LoginUser>, inserting each LoginUserId into the List<int> in turn.

Is there a more efficient way to handle this, or some sort of built in function for it?

Upvotes: 1

Views: 62

Answers (2)

Kacey
Kacey

Reputation: 99

Use LINQ

List<int> userIds = (from user in userList
                select user.LoginUserId).ToList();

Upvotes: 1

ChrisF
ChrisF

Reputation: 137118

You can use LINQ:

var userIds = loginUser.Select(l => l.LoginUserId);

Where loginUser is your list of LoginUser objects.

This will generate an IQueryable<int> which you can either enumerate as is or convert to a list (via .ToList())

Upvotes: 6

Related Questions