Michael Mankus
Michael Mankus

Reputation: 4788

Get an array of a field within an array of object containing that field

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?

Upvotes: 0

Views: 101

Answers (3)

ispiro
ispiro

Reputation: 27713

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.

Upvotes: 1

Alireza
Alireza

Reputation: 10486

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

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1502816

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

Upvotes: 5

Related Questions