简体   繁体   English

C#列表,从对象列表创建列表对象

[英]C# Lists, create list object from a list of objects

I have a list object like this 我有一个这样的列表对象

List<Site> lsite = GetSitesById(Id);

and the Site object is 并且Site对象是

public Site(int nId, string name, int Count)
        {
            Id = nId;
            Name = name;
            SiteOverrideCount = Count;
        }

What I need is List<int> OnlySites= which will have a list of only Site Id's 我需要的是List<int> OnlySites= ,它将只有一个站点ID的列表

How can I get only id's from the lsite object, dump them in a list object and assign that to List OnlySites 如何从lsite对象获取ID,将其转储到列表对象中并将其分配给List OnlySites

I am new at this, hope my question made sense. 我对此很陌生,希望我的问题有意义。

You need to use Linq Select method, eg: 您需要使用Linq Select方法,例如:

List<int> OnlySites = lsite.Select(s => s.Id).ToList();

This will produce a list of site Ids. 这将产生一个站点ID列表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM