简体   繁体   中英

Getting a variable from a list of objects

How would you get a variable from each object in a list?

I've got this so far:

void SortList()
{
    int j = modules.Count;
    string[] titles = new string[j];

    for (int i = 0; i > modules.Count; i++)
    {
        titles[i] = 
    }
}

And I'm trying to get the variable "code" from each object in modules.

thanks.

Implying modules is a list or an array,

void SortList()
{
    int j = modules.Count;
    string[] titles = new string[j];

    foreach (String title in modules)
    {
        titles[i] = title.code
    }
}

As stated by Cuong Le, you could also use Linq to get a shorter version (Depending of which .Net version you are on).

titles = modules.Select(x => x.code).ToArray();

您可以使用带有Select方法的简单代码使用LINQ:

titles = modules.Select(x => x.code).ToArray();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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