I want to store the result of select query in an array in C#. Please tell me how to get datatable values and store in an array. My select query result contains n rows and only one column.
Replace type with the data type of your single column (e.g. int, string, ...) and myField with the name of your single column.
var myArray = (from row in myDataTable.AsEnumerable()
select row.Field<type>("myField")).ToArray();
Using the magic of C#'s generics and type inference, your array will automatically have the correct data type (e.g. int[], string[], ...).
Try something like this
private void getData()
{
SqlCeConnection conn = new SqlCeConnection("data source='c:\\northwind.sdf'; mode=Exclusive;");
SqlCeDataAdapter da = new SqlCeDataAdapter("Select [Unit Price] from Products", conn);
DataTable dtSource = new DataTable();
da.Fill(dtSource);
DataRow[] dr = new DataRow[dtSource.Rows.Count];
dtSource.Rows.CopyTo(dr, 0);
double[] dblPrice= Array.ConvertAll(dr, new Converter<DataRow , Double>(DataRowToDouble));
}
public static double DataRowToDouble(DataRow dr)
{
return Convert.ToDouble(dr["Unit Price"].ToString());
}
DataTable mydt = new DataTable();
ArrayList aLrows = new ArrayList();
foreach (DataRow dataRow in mydt.Rows)
{
aLrows.Add(string.Join(";", dataRow.ItemArray.Select(item => item.ToString)));
}
Related
I need to do this in my codes;
Get data from 2 columns in a database (laborer and trx_date)
Place the extracted data to a DataTable
Explode the first column in the DataTable
Place exploded_laborer and trx_date to an array with
key->exploded_laborer
exploded=>trx_date
I am able to get to number 3 I just need to do number 4. My code is below:
private void GetLocalData()
{
const string sql = #"SELECT laborer, trx_date from tbl_jobs WHERE trx_date BETWEEN #fromDate AND #toDate";
var laborerDataTable = new DataTable();
using (var conn = new SqliteAccess().ConnectToSqlite())
{
using (var cmd = new SQLiteCommand(sql, conn))
{
conn.Open();
cmd.Parameters.AddWithValue("#fromDate", dtpFrom.Value.ToString("yyyy-MM-dd"));
cmd.Parameters.AddWithValue("#toDate", dtpTo.Value.ToString("yyyy-MM-dd"));
laborerDataTable.Load(cmd.ExecuteReader());
}
}
var exploded = new List<string>();
foreach (DataRow row in laborerDataTable.Rows)
{
exploded.Add(row["laborer"].ToString().Split('|')[0]);
}
}
Your help is very much appreciated.
I think you are supposed to create Dictionary<TKey,TValue> which represents a collection of keys and values. This might do the trick for you
laborerDataTable.AsEnumerable()
.Select(row => laborerDataTable.Columns.Cast<DataColumn>()
.ToDictionary(column => row[laborer] as string
column => row[trx_date] as string))
Thus the complete code might look like
private void GetLocalData()
{
const string sql = #"SELECT laborer, trx_date from tbl_jobs WHERE trx_date BETWEEN #fromDate AND #toDate";
var laborerDataTable = new DataTable();
using (var conn = new SqliteAccess().ConnectToSqlite())
{
using (var cmd = new SQLiteCommand(sql, conn))
{
conn.Open();
cmd.Parameters.AddWithValue("#fromDate", dtpFrom.Value.ToString("yyyy-MM-dd"));
cmd.Parameters.AddWithValue("#toDate", dtpTo.Value.ToString("yyyy-MM-dd"));
laborerDataTable.Load(cmd.ExecuteReader());
}
}
var LabDict = laborerDataTable.AsEnumerable()
.Select(row => laborerDataTable.Columns.Cast<DataColumn>()
.ToDictionary(column => row[laborer] as string
column => row[trx_date] as string))
}
Edit
This is just to create a dummy table.
static DataTable GetTable()
{
// Here we create a DataTable with four columns.
DataTable table = new DataTable();
table.Columns.Add("laborer", typeof(string));
table.Columns.Add("trx_date", typeof(string));
// Here we add five DataRows.
table.Rows.Add("Indocin", "12/12/2010");
table.Rows.Add("Enebrel", "12/1/2011");
table.Rows.Add("Hydralazine", "1/12/2012");
table.Rows.Add("Combivent", "11/12/2013");
table.Rows.Add("Dilantin", "12/11/2014");
return table;
}
normal core C# way
DataTable laborerDataTable = GetTable();
Dictionary<string, string> exploded = new Dictionary<string, string>();
foreach(DataRow row in laborerDataTable.Rows)
{
exploded.Add(row.Field<string>(0), row.Field<string>(1));
}
Also, how do I print each of the row to a console?
foreach(var dct in exploded)
{
Console.WriteLine(dct.Key + " Date is " + dct.Value);
}
If you are expecting the result to a Key-Value pair then why an array? why not a Dictionary<string, string>? You can try something like this :
Dictionary<string, string> laborerDict = laborerDataTable.AsEnumerable()
.ToDictionary(x => x.Field<string>("laborer"),
x => x.Field<string>("trx_date"));
Use in built HashMap in java refer the code below
HashMap map = new HashMap<>();
Map.put(key,value);
And to get data from map use
Map.get(key)
It has a lot of function, maybe you can refer them by searching Java API
when you want to have Key=>Value better you use Dictionary instead of List
var exploded = new Dictionary<string,string>();
foreach (DataRow row in laborerDataTable.Rows)
{
exploded.Add(row["laborer"].ToString(),(row["trx_date"].ToString());
}
I need write simple class in C#. I have 2 tables. But for understanding I use just 1 table.
public string[] GetCustOrders(int CustomerCODE)
{
SqlConnection myConn = new SqlConnection("server=(local);Initial Catalog=dbName;Integrated Security=True");
SqlDataAdapter myData = new SqlDataAdapter("CustOrdersOrdersDetails", myConn);
myData.SelectCommand.CommandType = CommandType.StoredProcedure;
myData.SelectCommand.Parameters.Add(new SqlParameter("#CustomerCODE", SqlDbType.Int, 0));
myData.SelectCommand.Parameters["#CustomerCODE"].Value = CustomerCODE;
// string[] as = string[6];
string[] as1 = string[3];
// string[] as2 = string[3];
DataSet ds = new DataSet();
myData.Fill(ds);
return as;
}
And my stored procedure code:
CREATE PROCEDURE CustOrdersOrdersDetails
#CustomerCODE int
AS
SELECT
Name,
Action,
Comments
FROM
System2
WHERE
Code = #CustomerCODE
The stored procedure will select just 1 row from the table. But I dont know how fromSqlDataAdapter` get each value of cell of this one row and give this value for my array as1.
Ex., "as[1]=" and after = I need give value of Action from selected row.
I know this simple, but I think... and think, that I can do this just give all values of my row to the DataSet and after that give each value of each cell to each string from my array. But I tray and cant finish this class...
Can anyone help?
int i = 0;
// For each table in the DataSet, print the row values.
foreach(DataTable table in ds.Tables)
{
foreach(DataRow row in table.Rows)
{
foreach (DataColumn column in table.Columns)
{
as[i]=row[column]);
i++;
}
}
}
can someone tells me how to do this?
I have this function in c#:
public string ConvertLocationTableToString()
{
int radius = 0;
string locationType = "marker";
DataTable dt = new DataTable();
Using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ToString()))
{
Using (SqlCommand cmd = new SqlCommand("SELECT lat=Latitude, lng=Longitude, FROM Locations", con))
{
con.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
Dictionary<string, object> row;
foreach (DataRow dr in dt.Rows)
{
row = new Dictionary<string, object>();
foreach (DataColumn col in dt.Columns)
{
row.Add(col.ColumnName, dr[col]);
}
rows.Add(row);
}
return serializer.Serialize(rows);
}
}
}
The table Locations contains two rows with latitude and lontitude values.
It produces string value of:
[{"lat":24.816925048828125,"lng":-107.37641906738281}
, {"lat":24.815664291381836,"lng":-107.38169097900391}]
.
But I want to produce the following:
[{"Coordinates": [{"lat":24.816925048828125,"lng":-107.37641906738281}], "Radius": 0,"LocationType": "marker"}
,{ "Coordinates": [{lat":24.815664291381836,"lng":-107.38169097900391}],"Radius": 0,"LocationType": "marker"}}]
Please notice that ‘Radius’ and ‘LocationType’ are not fields in the table.
Thank you for your help.
rubenc
You are serializing rows, which is returned from the table. If you created an object in C# that matches your desired output, then looped over the rows returned and set the relevant items, you could then serialize that.
In your case, the object would consist of:
- Coordinates - some type of list
- Radius - int I assume
- LocationType - guessing enum
Then you would create an arrray of these, and serialize the array.
i want to extract my table names and save it into variables this is my cod that return 3 answer:student, teacher and score. how can i change it to save these tree table name to 3 variable. thank you.
try
{
SqlDataReader myreader = null;
SqlCommand mycommand = new SqlCommand("select * FROM information_schema.tables WHERE table_type = 'BASE TABLE'", myconnect);
myreader = mycommand.ExecuteReader();
while (myreader.Read())
{
Console.WriteLine(myreader[2].ToString());
}
}
A simple builtin way is using Connection.GetSchema:
using (var con = new System.Data.SqlClient.SqlConnection(conStr))
{
con.Open();
DataTable schemaTable = con.GetSchema("Tables");
IList<string> allTableNames = schemaTable.AsEnumerable()
.Where(r => r.Field<string>("TABLE_TYPE") == "BASE TABLE")
.Select(r => r.Field<string>("TABLE_NAME"))
.ToList();
}
Now you have a List<string> with all table names which you can access via indexer or in a loop or create a comma separated list with string.Join:
string tNames = string.Join(",", allTableNames);
Console.Write("all tables in the given database: " + tNames);
You can use this :
string tableName ="" ; // Variable to stroe the table names
string connectionString = ""; //Your connectionstring
// get records from the table
string commandString =""; //Your query
// create the data set command object
// and the DataSet
SqlDataAdapter DataAdapter =new SqlDataAdapter(commandString, connectionString);
DataSet DataSet = new DataSet( );
// fill the DataSet object
DataAdapter.Fill(DataSet, "Customers");
// Get the one table from the DataSet
DataTable dataTable = DataSet.Tables[0];
// for each row in the table, display the info
foreach (DataRow dataRow in dataTable.Rows)
{
tableName = dataRow[0].tostring();
//...
}
if you want to save the result for future user or a different session then you can use any of the following to methods
first one
use the "insert" query to save the result one by one in the a different table that you would create specially for saving the data
you can put the insert command/statement directly into the for loop
second method
use the xml to store the value very simple and memory friendly
I Have modified #Doctor code to use ArrayList to store number of table name in single variables.
ArrayList alTableName = new ArrayList(); // Variable to stroe the table names
string connectionString = ""; //Your connectionstring
// get records from the table
string commandString =""; //Your query
// create the data set command object
// and the DataSet
SqlDataAdapter DataAdapter =new SqlDataAdapter(commandString, connectionString);
DataSet DataSet = new DataSet( );
// fill the DataSet object
DataAdapter.Fill(DataSet, "Customers");
// Get the one table from the DataSet
DataTable dataTable = DataSet.Tables[0];
// for each row in the table, display the info
foreach (DataRow dataRow in dataTable.Rows)
{
alTableName.Add(dataRow[0].tostring());
//...
}
I currently have a DataGridView which displays all the item. I would like to sum all the prices in the price column and then reflect the total in a label, 'TotalValueLabel'. What's wrong with my statement?
string query = "SELECT SUM (Price) FROM Bill";
OleDbDataAdapter dAdapter = new OleDbDataAdapter(query, DBconn);
DataTable source = new DataTable();
dAdapter.Fill(source);
TotalValueLabel.Text = source.ToString();
Your source is a DataTable so "source.ToString()" will not give you your result,
Try "source.Rows[0][0].ToString();".
DataTable object contains a list of DataRow objects which hold values for each row of your query result.
In your case however you might not need this. If you are looking for a single value you should use IDbCommand and call ExecuteScalar(). This will return the first value of the first row of your results.
Also try calling Dispose() on objects that implement IDisposable (like dbadapter, command, connection).
string query = "SELECT SUM (Price) FROM Bill";
using (System.Data.IDbCommand command = new System.Data.OleDb.OleDbCommand(query, DBconn))
{
object result = command.ExecuteScalar();
TotalValueLabel.Text = Convert.ToString(result);
}
DataTable is overkill for single value retrieval, besides your not even accessing the value correctly, better way is to use execute scalar:
var query = "SELECT SUM (Price) FROM Bill";
using (var cmd = new OleDbCommand(query, DBcon))
{
TotalValueLabel.Text = cmd.ExecuteScalar().ToString();
}