How to save SELECT sql query results in an array in C# Asp.net

后端 未结 6 606
时光取名叫无心
时光取名叫无心 2020-12-14 17:36

I have wrote this query to get some results, if I want to save the results in an array what I have to do? I want to use the values which are in col1 and col2 in an IF state

6条回答
  •  臣服心动
    2020-12-14 17:55

    Normally i use a class for this:

    public class ClassName
    {
        public string Col1 { get; set; }
        public int Col2 { get; set; }
    }
    

    Now you can use a loop to fill a list and ToArray if you really need an array:

    ClassName[] allRecords = null;
    string sql = @"SELECT col1,col2
                   FROM  some table";
    using (var command = new SqlCommand(sql, con))
    {
        con.Open();
        using (var reader = command.ExecuteReader())
        {
            var list = new List();
            while (reader.Read())
                list.Add(new ClassName { Col1 = reader.GetString(0), Col2 = reader.GetInt32(1) });
            allRecords = list.ToArray();
        }
    }
    

    Note that i've presumed that the first column is a string and the second an integer. Just to demonstrate that C# is typesafe and how you use the DataReader.GetXY methods.

提交回复
热议问题