0

I have an object like this:

public class SavedFileInfo
{
    public String Address;
    public Int32 DataPort;
    public Int32 AudioPort;
    public String Description;
    public String Filename;
}

And I have an array of those objects like this... SavedFileInfo[] mySFI;

How can I now get an array of the Filename field (such as string[] filenames) from within my collection of the SavedFileInfo objects?

3 Answers 3

5

Personally I'd use LINQ:

var files = mySFI.Select(x => x.Filename)
                 .ToArray();

Alternatively, there's Array.ConvertAll:

var files = Array.ConvertAll(mySFI, x => x.Filename);

As an aside, I would strongly advise you to use properties instead of fields. It's very easy to change your code to use automatically implemented properties:

public class SavedFileInfo
{
    public String Address { get; set; }
    public Int32 DataPort { get; set; }
    public Int32 AudioPort { get; set; }
    public String Description { get; set; }
    public String Filename { get; set; }
}
Sign up to request clarification or add additional context in comments.

2 Comments

I'm using the FileHelpers (www.filehelpers.com) library for reading and writing to files. That library is picky about wanting to use fields rather than properties. Otherwise I would completely agree with you.
@MichaelMankus: That's a really bad sign to start with, IMO. I would be very wary of libraries with such poor design decisions... it doesn't bode well for the implementation. Depending on how far down the path you are, you may want to see if there are alternatives.
1
String[] fileNames = new string[mySFI.Length];
for (int i = 0; i < mySFI.Length; i++)
    fileNames[i] = mySFI[i].Filename;

I might be missing something here, but if you really mean "How" to do it, and not "what's the simplest way to do it" (for that - see Skeet's answer) then it's important to know how to do it in a non-linq way as well. If I misunderstood you - my apologies.

Comments

0
SavedFileInfo[] mySFI;
var fileNameArr = mySFI.Select(p=>p.Filename).ToArray();

Comments

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.