create a dynamic resultset in csharp

To create a dynamic resultset in C#, you can use either ADO.NET or LINQ. Here's an example using ADO.NET:

main.cs
using System.Data;
using System.Data.SqlClient;

// create a SqlConnection object with the connection string
SqlConnection conn = new SqlConnection("ConnectionStringHere");

// create a SqlCommand object with the SQL query
SqlCommand cmd = new SqlCommand("SELECT * FROM MyTable", conn);

// create a DataTable object
DataTable dt = new DataTable();

// open the connection
conn.Open();

// create a SqlDataReader object and execute the query
SqlDataReader dr = cmd.ExecuteReader();

// loop through the rows and columns and add the data to the DataTable
for (int i = 0; i < dr.FieldCount; i++)
{
    dt.Columns.Add(dr.GetName(i), dr.GetFieldType(i));
}

while (dr.Read())
{
    DataRow row = dt.NewRow();

    for (int i = 0; i < dr.FieldCount; i++)
    {
        row[i] = dr.GetValue(i);
    }

    dt.Rows.Add(row);
}

// close the datareader and connection
dr.Close();
conn.Close();
886 chars
40 lines

Alternatively, you can use LINQ to create a dynamic resultset like this:

main.cs
using System.Data.Linq;

// create a DataContext object with the connection string
DataContext db = new DataContext("ConnectionStringHere");

// create a dynamic IQueryable object with the LINQ query
IQueryable<dynamic> rows = db.ExecuteQuery<dynamic>("SELECT * FROM MyTable");

// loop through the rows and columns and display the data
foreach (var row in rows)
{
    foreach (var column in row)
    {
        Console.WriteLine(column.Key + ": " + column.Value);
    }
}
472 chars
17 lines

Please note that while these approaches can create dynamic resultsets, it is generally recommended to use strongly-typed data models whenever possible for improved maintainability and type safety.

gistlibby LogSnag