Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a class into an array

Tags:

arrays

c#

class

I have a DisplayedData class ...

  public class DisplayedData
  {
    private int _key;
    private String _username;
    private String _fullName;
    private string _activated;
    private string _suspended;


    public int key { get { return _key; } set { _key = value; } }
    public string username { get { return _username; } set { _username = value; } }
    public string fullname { get { return _fullName; } set { _fullName = value; } }
    public string activated { get { return _activated; } set { _activated = value; } }
    public string suspended { get { return _suspended; } set { _suspended = value; } }
  }

And I want to to put the objects from this class into an array where all objects inside of this class should be converted into an String[]

I have..

DisplayedData _user = new DisplayedData();
String[] _chosenUser = _user. /* Im stuck here :)

or can I create an array where all the items inside are consist of variables of different datatype so that the integer remains an integer and so the strings too?

like image 597
Emmanuel Gabion Avatar asked Dec 19 '12 02:12

Emmanuel Gabion


1 Answers

You can create an array "with your own hands" (see Arrays Tutorial):

String[] _chosenUser = new string[] 
{ 
    _user.key.ToString(), 
    _user.fullname,
    _user.username,
    _user.activated,
    _user.suspended
};

Or you could use Reflection (C# Programming Guide):

_chosenUser = _user.GetType()
                    .GetProperties()
                    .Select(p =>
                        {
                            object value = p.GetValue(_user, null);
                            return value == null ? null : value.ToString();
                        })
                    .ToArray();
like image 126
horgh Avatar answered Nov 03 '22 02:11

horgh