简体   繁体   English

C#返回类数组中单个变量的数组

[英]C# Returning an array of a single variable within a class array

This may seem like a silly question but it's something I've never found an answer to. 这似乎是一个愚蠢的问题,但这是我从未找到答案的问题。

If I had an array of a class: 如果我有一个类的数组:

public class Folder
{
    public int Id { get; set; }
    public string Name { get; set; }
}

public Folder[] folders = new Folder[] {};

Is there a way to return all instances of ID without looping through and collecting them all? 有没有一种方法可以返回ID的所有实例,而无需循环遍历并收集所有实例?

If there isn't, what would you consider to be the best way of doing it so that I had an array of integers? 如果没有,那么您认为什么是最好的方式来使我拥有整数数组?

Thanks in advance, 提前致谢,

SumGuy SumGuy

ps If anyone can come up with a more appropriate title to this question that would be appreciated as well ps:如果有人可以为这个问题找到一个更合适的标题,也将不胜感激

You would have to loop through them some time in order to get a list of the Ids 您必须花一些时间遍历它们才能获得ID列表

You can get an array of Ids this way: 您可以通过以下方式获取ID数组:

int[] Ids = folders.Select(f => f.Id).ToArray();

(Must be using .NET 3.5 or above - the above performs the loop internally, so it is still looping) (必须使用.NET 3.5或更高版本-以上内容在内部执行循环,因此仍在循环)

public class Folder 
{     
    public int Id { get; set; }     
    public string Name { get; set; } }  

    // Try to avoid exposing data structure implementations publicly
    private Folder[] _folders = new Folder[] {};  

    public IEnumerable<Folder> Folders 
    {
        get 
        {
            return this._folders;
        }
    }

    public IEnumerable<int> FolderIds 
    {
        get 
        {
            // Linq knows all
            return this._folders.Select(f => f.Id);
        }
    }
}

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

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