How to convert an Object into an Array? (c#)

Asked

Viewed 1,435 times

4

I have the following class:

public string Nome;
public int Cpf;

 public string getNome() {        
    return Nome;         
}

 public void setNome(string nome) {
    this.Nome = nome;
}

public int getCpf() {
    return Cpf;
}

public void setCpf(int cpf) {
    this.Cpf = cpf;
}

how can I convert to an array?

I am wanting to create a function for the database where I need to pass only the table name and a Array or OrderedDictionary with the mapping of this class, to avoid having to change the query each time I add a new attribute to it, I have this function in phpand I’m trying to get through to c# and the first thing I need to do is this php I use the function implode() with array_keys() to separate the keys name of the fields in the database and the fields that will be inserted in the database. at the end I have a query thus INSERT INTO {$table} ( {$fields} ) VALUES ( {$values})"; that serves to insert values in any table.

  • 1

    What is your intention? What would you like to be added to the array? Nome and Cpf? In what order? These questions are just to show that what you are trying to do may not make much sense.

  • 1

    I’m building an application and this is for inserting users into bd, for while this class has 10 attributes throughout the development I believe I will need to add more information, I have a function that handles the insertion of this data based on the class, I do not want to need to rewrite the query's manually each time you add a new attribute to the class by mapping the class using a array or OrderedDictionary.

  • 3

    Since you want to do things dynamically, why not do it in PHP? In C#, although it is possible, this is not how it is done. Or even create classes in C#, do it all in array. Not that I think I should do this, but if you’re going to subvert the advantage of language, then subvert everything. If you feel better, use a Dictionary where you are classes. There are even other forms, but if it is to do wrong, it is not worth quoting.

  • 1

    because the application is in C#, the application is mobile, Here the staff gave me some tips right after I post the result.

3 answers

3

This is an extension that converts the properties of an object to a dictionary of objects having the name of the property as key:

    public static IDictionary<string, object> ToDictionary(this object obj)
    {
        IDictionary<string, object> result = new Dictionary<string, object>();
        var properties = TypeDescriptor.GetProperties(obj);
        foreach (PropertyDescriptor property in properties)
        {
            result.Add(property.Name, property.GetValue(obj));
        }
        return result;
    }

From there you can convert the dictionary to an array, via [dicionario].Values.ToArray();, for example.

  • I’ll try that too! although I’ve solved the problem, thanks for the tip!

2

You need to use an ORM as Entity Framework or Nhibernate, because the purpose of the ORM is to accurately map between the fields/properties of your object and the fields/properties of your table in the database.

The ORM itself creates and executes the insertion, update, etc. command and it is unnecessary for you to perform this work manually.


Useful references:

Site Nhibernate
Entity Framework 6 source code (and earlier)
Entity Framework 7 source code

  • 1

    i have a php function that performs this procedure with only 7 lines of code, use a framework to perform this process?! I am looking for functions similar to the one used in php to transcribe it in c#. Thanks more for the tip!

  • 2

    Yes, when you can read the references, because the benefits of these Orms go far beyond what you imagine. If it were advantageous to do using a function as you imagine, we would all be using such a function and not using ORM.

  • i understand, but in my case using a framework would be like killing a fly with a cannon.

0


I decided, instead of creating a Array() as I was thinking I listed using a Dictionary<string, string>. as follows:

//Cria uma bindingflag que armazena as propriedades da classe.
BindingFlags bindingFlags = BindingFlags.Public | 
    BindingFlags.NonPublic | 
    BindingFlags.Instance | 
    BindingFlags.Static;

Usuario user = new Usuario();

user.setNome("Something");
user.setCPF(123456789);

var newUser = new Dictionary<string, string>();

foreach (FieldInfo field in typeof(Usuario).GetFields(bindingFlags))
{
      print(field.Name + " Values => " + field.GetValue(user).ToString());
      newUser.Add(field.Name, field.GetValue(user).ToString());
}

Now I can build the querys dynamically as I do in php, and I no longer need to rewrite querys since I can only list them automatically with the class itself, only care that the variable name should be the same name as the field in the table in the database.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.