开发者

C# Returning an array of a single variable within a class array

开发者 https://www.devze.com 2023-02-01 05:51 出处:网络
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:

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?

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

p.s. If anyone can come up with a more appropriate title to this question that would be appreciated as well


You would have to loop through them some time in order to get a list of the Ids

You can get an array of Ids this way:

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)


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);
        }
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号