0

i want to create a c# object dynamically with data from sql select query

Query result example:

Percentage  Way

    47.64   DPAD_UP
    35.20   DPAD_DOWN
    8.67    LEFT_RIGHT_MENU
    5.54    MENU
    2.88    MENU_KRYESORE
    0.06    EPG_CLICK

from this query i want to create te following object:

data = new object[] { 
    new object[] { "DPAD_UP", 47.64 }, 
    new object[] { "DPAD_DOWN", 35.20 }, 
    new object[] { "LEFT_RIGHT_MENU", 8.67 },
    new object[] { "MENU", 5.54 }, 
    new object[] { "MENU_KRYESORE", 2.88 }, 
    new object[] { "EPG_CLICK", 0.06 } 
}

How to do this?

kurochenko
  • 1,214
  • 3
  • 19
  • 43
Maria Agaci
  • 281
  • 2
  • 3
  • 11
  • 1
    google Linq and Entity Framework. Entity Framework automatically turns your SQL objects into C# objects. – DLeh Feb 04 '15 at 13:49
  • What have you tried so far? Please try something on your own and if you are stuck somewhere than kindly let us know. We would be happy to help you. – Prerak Sola Feb 04 '15 at 13:49
  • Take a look at [Expando Object](https://msdn.microsoft.com/en-us/library/system.dynamic.expandoobject%28v=vs.110%29.aspx) – Mahesh Feb 04 '15 at 13:49
  • If you are immediately using this object, you can use anonymous types. – ryanyuyu Feb 04 '15 at 13:49
  • 2
    Have a look at Dapper: https://github.com/StackExchange/dapper-dot-net –  Feb 04 '15 at 13:49

1 Answers1

3

Are you looking for something like that? Just direct reading (I've assumed that you use MS SQL DBMS)

      List<Object[]> results = new List<Object[]>();

      using (SqlConnection conn = new SqlConnection("Your connection String")) {
        conn.Open();

        using (SqlCommand query = new SqlCommand("your query", conn)) {
          //TODO: May be you have parameters - assign them here...

          using (var reader = query.ExecuteReader()) {
            while (reader.Read()) {
              results.Add(new Object[] {reader.GetValue(0), reader.GetValue(1)});
            }
          }
        }
      }

      data = results.ToArray(); 
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
  • I m getting this error An exception of type 'System.ArgumentException' occurred in System.Data.dll but was not handled in user code Additional information: Format of the initialization string does not conform to specification starting at index 0. – Maria Agaci Feb 04 '15 at 14:57
  • @Maria Agaci: Check your connection string. http://stackoverflow.com/questions/16203376/format-of-the-initialization-string-does-not-conform-to-to-specification-startin – Dmitry Bychenko Feb 04 '15 at 15:00