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?
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);
}
}
}
精彩评论