Can I create an anonymous type collection from a DataReader?

后端 未结 4 540
没有蜡笔的小新
没有蜡笔的小新 2021-02-09 06:22

I have this code:

var query = \"SELECT * FROM Cats\";

var conn = new SqlConnection(sqlConnectionString);

conn.Open();

var cmd = new SqlCommand(query);
var rea         


        
4条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-02-09 07:15

    Here is an example of doing it with dynamic (which I think is easier to work with) but some may feel does not adhere to the letter of your question.

    Call it like this:

    var result = SelectIntoList("SELECT * FROM Cats",sqlconnectionString);
    

    You could (like I did) put it into a static class in a separate file for easier maintanence.

    public static IEnumerable SelectIntoList(string SQLselect, string connectionString, CommandType cType = CommandType.Text)
    {
      using (SqlConnection conn = new SqlConnection(connectionString))
      {
        using (SqlCommand cmd = conn.CreateCommand())
        {
          cmd.CommandType = cType;
          cmd.CommandText = SQLselect;
    
          conn.Open();
    
          using (SqlDataReader reader = cmd.ExecuteReader())
          {
    
            if (reader.Read())  // read the first one to get the columns collection
            {
              var cols = reader.GetSchemaTable()
                           .Rows
                           .OfType()
                           .Select(r => r["ColumnName"]);
    
              do
              {
                dynamic t = new System.Dynamic.ExpandoObject();
    
                foreach (string col in cols)
                {
                  ((IDictionary)t)[col] = reader[col];
                }
    
                yield return t;
              } while (reader.Read());
            }
          }
    
          conn.Close();
        }
      }
    }
    

提交回复
热议问题