1

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

2 Answers 2

7

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)

Sign up to request clarification or add additional context in comments.

2 Comments

+1 for "the above performs the loop internally, so it is still looping"
It's a good point that there must be a loop somewhere, but I think for the OPs purposes he was trying to avoid writing the loop himnself and this satisfies that. Linq is awesome basically :)
2
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);
        }
    }
}

1 Comment

I think it's important to point out that the actual traversing of the Folders array happens when the returned IEnumerable is iterated over, and this happens every time the IEnumerable is iterated over. This can have some consequences depending on your application. In some cases, you may want to put an extra ToArray() at the end of the expression.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.