[英]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. 我的代码定义了一个LoginUser对象,其中包含许多列
LoginUserId, UserName, ActiveFlag
, LoginUserId, UserName, ActiveFlag
等。我有这些对象的List<LoginUser>
。
Right now, my code creates a List<int>
, then iterates through the List<LoginUser>
, inserting each LoginUserId
into the List<int>
in turn. 现在,我的代码创建一个
List<int>
,然后遍历List<LoginUser>
,依次将每个LoginUserId
插入到List<int>
中。
Is there a more efficient way to handle this, or some sort of built in function for it? 有没有更有效的方法来处理此问题,或者有某种内置函数?
You can use LINQ: 您可以使用LINQ:
var userIds = loginUser.Select(l => l.LoginUserId);
Where loginUser
is your list of LoginUser objects. 其中
loginUser
是LoginUser对象的列表。
This will generate an IQueryable<int>
which you can either enumerate as is or convert to a list (via .ToList()
) 这将生成一个
IQueryable<int>
,您可以按原样枚举或转换为列表(通过.ToList()
)。
Use LINQ 使用LINQ
List<int> userIds = (from user in userList
select user.LoginUserId).ToList();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.