I'm using Linq to return data from an XML file to a DataTable and that works. But now I'm trying to modify the code to loop through the DataTable. I created a custom class to model the data and have a List in my model. When I loop through the DataTable to display records it displays System.Collections.Generic.List`1[System.String] instead of the actual data. I'm not sure what to search to find the answer.
Snippet:
foreach (DataRow row in tbl.Rows)
{
myList = row["myList"] + ", " + myList;
}
The myList column is the List. I hope this makes sense.
Edited:
public static DataTable LINQToDataTable<T>(IEnumerable<T> varlist)
{
DataTable dtReturn = new DataTable();
// column names
PropertyInfo[] oProps = null;
if (varlist == null) return dtReturn;
foreach (T rec in varlist)
{
// Use reflection to get property names, to create table, Only first time, others will follow
if (oProps == null)
{
oProps = ((Type)rec.GetType()).GetProperties();
foreach (PropertyInfo pi in oProps)
{
Type colType = pi.PropertyType;
if ((colType.IsGenericType) && (colType.GetGenericTypeDefinition() == typeof(Nullable<>)))
{
colType = colType.GetGenericArguments()[0];
}
dtReturn.Columns.Add(new DataColumn(pi.Name, colType));
}
}
DataRow dr = dtReturn.NewRow();
foreach (PropertyInfo pi in oProps)
{
dr[pi.Name] = pi.GetValue(rec, null) == null ?DBNull.Value :pi.GetValue
(rec,null);
}
dtReturn.Rows.Add(dr);
}
return dtReturn;
}
hobbiesList = (List<string>)row["hobbies"];
foreach (var item in hobbiesList)
{
hobbies.Add(item.ToString());
}
hobby = string.Join(", ", hobbies.ToArray());
hobbies.Clear();
I had to do the above to get it to work. I then add hobby to my output array.
Related
I have a Janus Grid with a checkbox in each row and wanna copy selected row(s) to a DataRowCollection or to DataRow[] .this is my way but not completed and not worked:
also this grid has group on one field and I use 2 loop for group and childs.
gridEX1.DataSource = dtALL;//dtALL is a data table fill with select sql command
DataRowCollection dr
DataRow dr2=dtALL.NewRow();
foreach (Janus.Windows.GridEX.GridEXRow g in gridEX1.GetRows())
{
foreach (Janus.Windows.GridEX.GridEXRow r in g.GetChildRows())
{
if ((bool)r.Cells["sendALL"].Value == true && r.Cells["DocTitle"].Value.ToString() == DocTitle)
{
for(int i=0;i<r.Cells.Count;i++)
if(r.Cells[i].GetType()==typeof(TextBox))
{
dr2[i] = r.Cells[i].Value;
}
dr.Add(dr2);
}
}
}
I figured out this way and solved my problem:
DataTable dt1copy = new DataTable();
dt1copy.Columns.Add("DocTitle");
dt1copy.Columns.Add("DocDetails");
dt1copy.Columns.Add("ExpLenght");
dt1copy.Columns.Add("ReqDate");
dt1copy.Columns.Add("ReqTypeDetailsTitle");
dt1copy.Columns.Add("ReqTypeTitle");
dt1copy.Columns.Add("UnitsTitle");
dt1copy.Columns.Add("DocType");
dt1copy.Columns.Add("DocSuffix");
dt1copy.Columns.Add("FKGID");
dt1copy.Columns.Add("Id");//id of docinreq tbl
DataRow dr2;
DataRowCollection dr = dt1copy.Rows;
string DocTitle = gridEX1.CurrentRow.Cells["DocTitle"].Value.ToString();
foreach (Janus.Windows.GridEX.GridEXRow g in gridEX1.GetRows())
{
foreach (Janus.Windows.GridEX.GridEXRow r in g.GetChildRows())
{
try
{
if ((bool)r.Cells["sendALL"].Value == true && r.Cells["DocTitle"].Value.ToString() == DocTitle)
{
dr2 = dt1copy.NewRow();
for (int i = 0, j = 0; i < r.Cells.Count; i++)
{
if (r.Cells[i].Column.BoundMode != Janus.Windows.GridEX.ColumnBoundMode.UnboundFetch)//select only bounded column from grid
{
dr2[j] = r.Cells[i].Value.ToString();
j++;
}
}
dt1copy.Rows.Add(dr2);
}
}
catch (Exception) { }
}
}
dr = dt1copy.Rows;
In below code, if(_drone["CODE"] =="zen") inside the for loop is not working,eventhough _drone["code"] contain zen.
Only those records with value zen .nedd to be added to_dr (_abc.rows.ans(_dr)
public DataTable InitInGroup(DataTable _dtdoctor, string _Folio, string _IsCom = "No", string _CODE = "")
{
DataTable _abc = GetDoc("~", "~", "~", "~");
if (_dtdoctor != null)
{
foreach (DataRow _drone in _dtdoctor.Rows)
{
if (_drone["CODE"] == "zen"
Edit
Not working with the one you mentioned .As above another scenario stated below.I want to compare the session value with the database value
foreach (DataRow dr28 in _DTU_ABC.Rows)
{
string ss = HttpContext.Current.Session["ADMIN"].ToString();
IF (dr28[_CODE].ToString == ss)
{
cmd28.Parameters.Clear();
OracleHelper.CreateParameter(ref cmd28, ref param28, "#NUMBER", DbType.String, ParameterDirection.Input, dr28["Number"].ToString());
OracleHelper.CreateParameter(ref cmd28, ref param28, "#SITECODE", DbType.String, ParameterDirection.Input, dr28["CODE"].ToString());
cmd28.ExecuteNonQuery();
}
}
_drone["CODE"] returns an object. Try this instead:
if (_drone["CODE"].ToString() == "zen")
I want to data in gridview for a particular mail_id. but wheneven i add this where condition its not showing anything. please help
if (!IsPostBack)
{
var mail = lblmail.Text;
var result = from test in je.jobposting orderby test.post_date where test.c_j_email==mail select test;
foreach (var items in result)
{
gvjob.DataSource = result;
gvjob.DataBind();
}
}
Is this better?
{
var mail = lblmail.Text;
// here, I assume jobposting is a DataTable
if (0 < je.jobposting.Rows.Count) {
var result = from test in je.jobposting orderby test.post_date where test.c_j_email==mail select test;
if (result.Any()) {
gvjob.DataSource = result;
gvjob.DataBind();
} else {
Response.WriteLine("No Match for c_j_email=" + mail + ".");
}
} else {
Response.WriteLine("<b>No Data in jobposting DataTable!</b>");
}
}
I am trying to use following code to create the PIVOT but its not working.
It's giving me compile time error. I don't know linq so unable to use it.
Please help :
DataTable Pivot(DataTable dt, DataColumn pivotColumn, DataColumn pivotValue) {
// find primary key columns
//(i.e. everything but pivot column and pivot value)
DataTable temp = dt.Copy();
temp.Columns.Remove( pivotColumn.ColumnName );
temp.Columns.Remove( pivotValue.ColumnName );
string[] pkColumnNames = temp.Columns.Cast(<DataColumn>)
.Select( c => c.ColumnName )
.ToArray();
// prep results table
DataTable result = temp.DefaultView.ToTable(true, pkColumnNames).Copy();
result.PrimaryKey = result.Columns.Cast(<DataColumn>).ToArray();
dt.AsEnumerable()
.Select(r =>; r[pivotColumn.ColumnName].ToString())
.Distinct().ToList()
.ForEach (c => result.Columns.Add(c, pivotColumn.DataType));
// load it
foreach( DataRow row in dt.Rows ) {
// find row to update
DataRow aggRow = result.Rows.Find(
pkColumnNames
.Select( c => row[c] )
.ToArray() );
// the aggregate used here is LATEST
// adjust the next line if you want (SUM, MAX, etc...)
aggRow[row[pivotColumn.ColumnName].ToString()] = row[pivotValue.ColumnName];
}
return result;
}
Code from : http://michaeljswart.com/2011/06/forget-about-pivot/
Moreover it tried to use following code, it works well except for it is not giving total sum for Value Column
public DataTable GetInversedDataTable(DataTable table, string columnX, string columnY, string columnZ, string nullValue, bool sumValues)
{
//Create a DataTable to Return
DataTable returnTable = new DataTable();
DataTable tempTable = table.Clone();
if (string.IsNullOrEmpty(columnX))
{
columnX = table.Columns[0].ColumnName;
}
tempTable.Columns.Remove(columnX);
//Add a Column at the beginning of the table
//returnTable.Columns.Add(columnY);
returnTable = tempTable.Clone();
//Read all DISTINCT values from columnX Column in the provided DataTale
List<string> columnXValues = new List<string>();
foreach (DataRow dr in table.Rows)
{
string columnXTemp = dr[columnX].ToString();
if (!columnXValues.Contains(columnXTemp))
{
//Read each row value, if it's different from others provided, add to the list of values and creates a new Column with its value.
columnXValues.Add(columnXTemp);
returnTable.Columns.Add(columnXTemp);
}
}
//Verify if Y and Z Axis columns re provided
if (!string.IsNullOrEmpty(columnY) && !string.IsNullOrEmpty(columnZ))
{
//Read DISTINCT Values for Y Axis Column
List<string> columnYValues = new List<string>();
foreach (DataRow dr in table.Rows)
{
if (!columnYValues.Contains(dr[columnY].ToString()))
{
columnYValues.Add(dr[columnY].ToString());
}
}
//Loop all Column Y Distinct Value
foreach (string columnYValue in columnYValues)
{
//Creates a new Row
DataRow drReturn = returnTable.NewRow();
drReturn[0] = columnYValue;
//foreach column Y value, The rows are selected distincted
DataRow[] rows = table.Select((columnY + "='") + columnYValue + "'");
//Read each row to fill the DataTable
foreach (DataRow dr in rows)
{
string rowColumnTitle = dr[columnX].ToString();
//Read each column to fill the DataTable
foreach (DataColumn dc in returnTable.Columns)
{
if (dc.ColumnName == rowColumnTitle)
{
//If Sum of Values is True it try to perform a Sum
//If sum is not possible due to value types, the value displayed is the last one read
if (sumValues)
{
try
{
drReturn[rowColumnTitle] = Convert.ToDecimal(drReturn[rowColumnTitle]) + Convert.ToDecimal(dr[columnZ]);
}
catch
{
drReturn[rowColumnTitle] = dr[columnZ];
}
}
else
{
drReturn[rowColumnTitle] = dr[columnZ];
}
}
}
}
returnTable.Rows.Add(drReturn);
}
}
else
{
throw new Exception("The columns to perform inversion are not provided");
}
//if a nullValue is provided, fill the datable with it
if (!string.IsNullOrEmpty(nullValue))
{
foreach (DataRow dr in returnTable.Rows)
{
foreach (DataColumn dc in returnTable.Columns)
{
if (string.IsNullOrEmpty(dr[dc.ColumnName].ToString()))
{
dr[dc.ColumnName] = nullValue;
}
}
}
}
return returnTable;
}
GetInversedDataTable(dtNormal, "Dated", "OrderStatus", "Qty", " ", true);
Please help :)
Here is the code with the compilation errors corrected:
DataTable Pivot(DataTable dt, DataColumn pivotColumn, DataColumn pivotValue) {
// find primary key columns
//(i.e. everything but pivot column and pivot value)
DataTable temp = dt.Copy();
temp.Columns.Remove( pivotColumn.ColumnName );
temp.Columns.Remove( pivotValue.ColumnName );
string[] pkColumnNames = temp.Columns.Cast<DataColumn>()
.Select( c => c.ColumnName )
.ToArray();
// prep results table
DataTable result = temp.DefaultView.ToTable(true, pkColumnNames).Copy();
result.PrimaryKey = result.Columns.Cast<DataColumn>().ToArray();
dt.AsEnumerable()
.Select(r => r[pivotColumn.ColumnName].ToString())
.Distinct().ToList()
.ForEach (c => result.Columns.Add(c, pivotColumn.DataType));
// load it
foreach( DataRow row in dt.Rows ) {
// find row to update
DataRow aggRow = result.Rows.Find(
pkColumnNames
.Select( c => row[c] )
.ToArray() );
// the aggregate used here is LATEST
// adjust the next line if you want (SUM, MAX, etc...)
aggRow[row[pivotColumn.ColumnName].ToString()] = row[pivotValue.ColumnName];
}
return result;
}
I changed Cast(<DataColumn>) to Cast<DataColumn>() in two locations and got rid of the semicolon in the middle of a lambda expression. The second part of your question is a little trickier. You may want to ask it as its own question.
Good one., but you might want to replace the below line
.ForEach (c => result.Columns.Add(c, pivotColumn.DataType));
with this (change pivotColumn to pivotValue)
.ForEach (c => result.Columns.Add(c, pivotValue.DataType));
Works perfectly for my requirement.
Im trying to write a method which will allow me to search different DataTables, over different columns.
So far i have the following:
string selectedValue;
string searchColumn;
string targetColumn;
var results = (from a in dt.AsEnumerable()
where a.Field<string>(searchColumn) == selectedValue
select new
{
targetColumn = a.Field<string>(targetColumn)
}).Distinct();
Which kind of gets the job done, but I'm left with the column name as targetColumn rather than the actual column name I want.
Is there any way to resolve this?
Thanks in advance
CM
I make a LINQ to Datatables
public List<DataRow> Where(this DataTable dt, Func<DataRow, bool> pred)
{
List<DataRow> res = new List<DataRow>();
try {
if (dt != null && dt.Rows.Count > 0) {
for (i = 0; i <= dt.Rows.Count - 1; i++) {
if (pred(dt(i))) {
res.Add(dt(i));
}
}
}
} catch (Exception ex) {
PromptMsg(ex);
}
return res;
}
Usage :
var RowsList = dt.Where(f => f("SomeField").toString() == "SomeValue" ||
f("OtherField") > 5);