将sql select结果转换为c#object

时间:2015-02-04 13:47:34

标签: c# sql object

我想用sql select query

中的数据动态创建一个c#对象

查询结果示例:

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
从这个查询

我想创建以下对象:

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

怎么做?

1 个答案:

答案 0 :(得分:3)

你正在寻找类似的东西吗?只是直接阅读(我假设您使用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();