I'm trying to update a DataTable that is part of a DataSet. I search through the table using a DataRow then pass the value into a DataRow for updating to the DataSet, however this is not working, can anyone advise where I am going wrong?
foreach(DataRow drHierarchyTrueValueList in ds.Tables["HierarchyTypeValueList"].Rows)
{
foreach(DataRow drHierarchyListToUpdate in ds.Tables["Hierarchy"].Rows)
{
if (drHierarchyListToUpdate["HierarchyParent"] ==
drHierarchyTrueValueList["HierarchyValueDescription"] &&
Convert.ToInt32(drHierarchyListToUpdate["HierarchyParentType"]) != 0)
{
drHierarchyListToUpdate["HierarchyParentValue"] =
Convert.ToInt32(drHierarchyTrueValueList["HierarchyTrueValue"]);
}
}
ds.Tables["Hierarchy"].AcceptChanges();
}
I changed it to this, and it worked:
foreach(DataRow drHierarchyListToUpdate in ds.Tables["Hierarchy"].Rows)
{
string HierarchyParent = drHierarchyListToUpdate["HierarchyParent"].ToString();
string HierarchyValueDescription = drHierarchyTrueValueList["HierarchyValueDescription"].ToString();
int HierarchyParentType = Convert.ToInt32(drHierarchyListToUpdate["HierarchyParentType"]);
if (HierarchyParent == HierarchyValueDescription && HierarchyParentType != 0)
{
drHierarchyListToUpdate["HierarchyParentValue"] = Convert.ToInt32(drHierarchyTrueValueList["HierarchyTrueValue"]);
}
else if (HierarchyParent != HierarchyValueDescription && HierarchyParentType == 0)
{
drHierarchyListToUpdate["HierarchyParentValue"] = 0;
}
}
ds.Tables["Hierarchy"].AcceptChanges();
Related
I am using below query
DataRow[] oFilteredRows =
oTrgFTPTrigList.Select($"ftpPath='{oSrcRow["ftpPath"]}'
and ftpUserName='{oSrcRow["ftpUserName"]}'");
But it fails since ftpPath is url ftp://testURL/
I need to filter and get records with same data as of source (Comparing target and source DataBases)
Here is the answer.
I have converted data like below.
string ftpPath = Uri.EscapeUriString(oSrcRow["ftpPath"].ToString());
Here is the full code sample.
public DataTable compareFTPTriggers(string targetConnectionString)
{
DataTable oFTPTriggerTableDiffs = new DataTable("oFTPTriggerDiffs");
oFTPTriggerTableDiffs.Columns.Add("oFTPTriggerID");
oFTPTriggerTableDiffs.Columns.Add("oFTPTriggerName");
oFTPTriggerTableDiffs.Columns.Add("Comments");
try
{
deFTPTrigger oSrcFTPTrigger = new deFTPTrigger(m_connectString, m_externalUserID);
DataTable oSrcFTPTrigList = oSrcFTPTrigger.getAllFTPTriggers();
string systemUserID = clsSettings.systemUserID(targetConnectionString);
deFTPTrigger oTrgFTPTrigger = new deFTPTrigger(targetConnectionString, systemUserID);
DataTable oTrgFTPTrigList = oTrgFTPTrigger.getAllFTPTriggers();
foreach (DataRow oSrcRow in oSrcFTPTrigList.Rows)
{
string ftpPath = Uri.EscapeUriString(oSrcRow["ftpPath"].ToString());
DataRow[] oFilteredRows = oTrgFTPTrigList.Select($"ftpPath= '{ftpPath}' and ftpUserName='{oSrcRow["ftpUserName"]}'");
string sKey = $"{oSrcRow["ftpPath"]} - {oSrcRow["ftpUserName"]}";
if (oFilteredRows.Length == 0)
{
oFTPTriggerTableDiffs.Rows.Add(oSrcRow["ftpTriggerID"], sKey, "Addition");
}
else
{
if (
oSrcRow["ftpPassword"].ToString() != oFilteredRows[0]["ftpPassword"].ToString() ||
oSrcRow["waitTime"].ToString() != oFilteredRows[0]["waitTime"].ToString() || oSrcRow["waitType"].ToString() != oFilteredRows[0]["waitType"].ToString() ||
oSrcRow["definitionID"].ToString() != oFilteredRows[0]["definitionID"].ToString() || oSrcRow["variableName"].ToString() != oFilteredRows[0]["variableName"].ToString() ||
oSrcRow["enabled"].ToString() != oFilteredRows[0]["enabled"].ToString() || oSrcRow["globalName"].ToString() != oFilteredRows[0]["globalName"].ToString()
)
{
oFTPTriggerTableDiffs.Rows.Add(oSrcRow["ftpTriggerID"], sKey, "Properties are different");
}
}
}
}
catch (Exception ex)
{
// m_oErrorProvider.writeError(ex.Message);
}
DataView dvSorted = oFTPTriggerTableDiffs.DefaultView;
dvSorted.Sort = "oFTPTriggerName ASC";
oFTPTriggerTableDiffs = dvSorted.ToTable();
return (oFTPTriggerTableDiffs);
}
I am trying to insert around 5000 records in database using foreach loop. It is taking around 10 min which is not acceptable as per the requirement. I also thought about the approach in which first insert the records in a datatable and then converting it into XML pass it to stored procedure which do the insertion. But unfortunately it is not getting fit in my situation. Now i am doing the same thing using parallel.foreach but after inserting 10 records i am getting "Unique constraint violation for the primary key" error msg. As i am new to parallel programming so not getting the solution for it. Below is my code that i have done so for.
public ActionResult ChannelBulkUpload(HttpPostedFileBase excelFile)
{
bool flag = true;
string path = Server.MapPath("~/Content/UploadFolder/" + excelFile.FileName);
if (System.IO.File.Exists(path))
{
System.IO.File.Delete(path);
}
excelFile.SaveAs(path);
DataTable dt = GetDataTableFromExcel(excelFile, true);
ParallelOptions options = new ParallelOptions
{
MaxDegreeOfParallelism = 4
};
Parallel.ForEach(dt.AsEnumerable(), row =>
{
flag = true;
decimal Key = 0;
string value = "";
decimal channelMstKey = 0;
decimal channelGrpMstKey = 0;
decimal srcFuncKey = 0;
string ExcelMasterChDisplayName = row["MASTER_CHANNEL_DISPLAY_NAME"].ToString();
string ExcelGenreValue = row["GENRE"].ToString();
string ExcelAdsharpValue = row["ADSHARP"].ToString();
string ExcelClusterValue = row["CLUSTER"].ToString();
string ExcelNetworkValue = row["NETWORK"].ToString();
string ExcelBroadCastValue = row["BROADCAST"].ToString();
string ExcelFunctionalAreaname = row["FUNCTIONAL_AREA"].ToString();
string[] Ch_Grp_types = { "GENRE", "ADSHARP", "CLUSTER", "NETWORK", "PLATFORM" };
BarcDataContext bc = new BarcDataContext();
srcFuncKey = bc.REF_SRC_FUNC_AREA.Where(m => m.SRC_FUNC_AREA == ExcelFunctionalAreaname).FirstOrDefault().SRC_FUNC_KEY;
for (int j = 0; j < Ch_Grp_types.Length && flag; j++)
{
if (Ch_Grp_types[j] == "GENRE")
{
Key = 1;
value = ExcelGenreValue;
}
else if (Ch_Grp_types[j] == "NETWORK")
{
Key = 2;
value = ExcelNetworkValue;
}
else if (Ch_Grp_types[j] == "ADSHARP")
{
Key = 3;
value = ExcelAdsharpValue;
}
else if (Ch_Grp_types[j] == "CLUSTER")
{
Key = 4;
value = ExcelClusterValue;
}
else if (Ch_Grp_types[j] == "PLATFORM")
{
Key = 5;
value = ExcelBroadCastValue;
}
DIM_CHANNEL_MST objChMst = bc.DIM_CHANNEL_MST.Where(m => m.CHANNEL_MST_NAME_UPPER == ExcelMasterChDisplayName.ToUpper().Trim()).FirstOrDefault();
if (objChMst == null)
{
flag = false;
}
else
{
if (!string.IsNullOrEmpty(value))
{
var query =
(from A in bc.XREF_CH_GRP_DET_TAG
join B in bc.XREF_CH_GRP_MST_TAG on A.CH_GRP_MST_KEY equals B.CH_GRP_MST_KEY
where A.IS_ACTIVE == "Y" && B.IS_ACTIVE == "Y" && B.CH_GRP_TYPE_KEY == Key && B.CH_GRP_MST_NAME_UPPER == value.ToUpper()
select new XrefChannelGrpDetailTagVM
{
channelGrpDetKey = A.CH_GRP_DET_KEY,
channelGrpMasterNameUpper = B.CH_GRP_MST_NAME_UPPER,
}).Distinct().ToList();
var query2 =
(from A in bc.XREF_CH_GRP_DET_TAG
join B in bc.XREF_CH_GRP_MST_TAG on A.CH_GRP_MST_KEY equals B.CH_GRP_MST_KEY
where A.CHANNEL_MST_KEY == objChMst.CHANNEL_MST_KEY && B.CH_GRP_TYPE_KEY == Key && B.SRC_FUNC_KEY == srcFuncKey
select new XrefChannelGrpDetailTagVM
{
sr_no = A.SR_NO,
channelMstKey = A.CHANNEL_MST_KEY,
channelGrpDetKey = A.CH_GRP_DET_KEY,
channelGrpMstKey = A.CH_GRP_MST_KEY,
srcFuncKey = B.SRC_FUNC_KEY,
channelGrpTypeKey = B.CH_GRP_TYPE_KEY
}).Distinct().ToList();
XREF_CH_GRP_MST_TAG objXrefChGrpMst = bc.XREF_CH_GRP_MST_TAG.Where(m => m.CH_GRP_TYPE_KEY == Key && m.SRC_FUNC_KEY == srcFuncKey && m.CH_GRP_MST_NAME_UPPER == value.ToUpper()).FirstOrDefault();
if (objXrefChGrpMst != null)
{
channelMstKey = objChMst.CHANNEL_MST_KEY;
channelGrpMstKey = objXrefChGrpMst.CH_GRP_MST_KEY;
XREF_CH_GRP_DET_TAG objGrpDetail = new XREF_CH_GRP_DET_TAG();
if (query.Count == 0)
{
objGrpDetail.CH_GRP_DET_KEY = Get_Max_Of_Ch_Grp_Det_Key();
}
else
{
foreach (var detKey in query)
{
if (detKey.channelGrpMasterNameUpper == value.ToUpper())
{
objGrpDetail.CH_GRP_DET_KEY = detKey.channelGrpDetKey;
}
else
{
objGrpDetail.CH_GRP_DET_KEY = Get_Max_Of_Ch_Grp_Det_Key();
}
}
}
if (query2.Count > 0)
{
foreach (var abc in query2)
{
if (abc.channelMstKey == objChMst.CHANNEL_MST_KEY && abc.srcFuncKey == srcFuncKey && abc.channelGrpTypeKey == Key)
{
if (abc.channelGrpDetKey == objGrpDetail.CH_GRP_DET_KEY && abc.channelGrpMstKey == objXrefChGrpMst.CH_GRP_MST_KEY)
{
//Reject
}
else
{
//Update
XREF_CH_GRP_DET_TAG obj = bc.XREF_CH_GRP_DET_TAG.Where(m => m.SR_NO == abc.sr_no).FirstOrDefault();
obj.CH_GRP_DET_KEY = objGrpDetail.CH_GRP_DET_KEY;
obj.CH_GRP_MST_KEY = objXrefChGrpMst.CH_GRP_MST_KEY;
objGrpDetail.CREATE_DATE = DateTime.Now;
objGrpDetail.LAST_UPD_DATE = DateTime.Now;
objGrpDetail.IS_ACTIVE = "Y";
bc.SaveChanges();
}
}
else
{
//Insert
objGrpDetail.CH_GRP_MST_KEY = channelGrpMstKey;
objGrpDetail.CHANNEL_MST_KEY = channelMstKey;
objGrpDetail.SR_NO = Get_Max_Of_XREF_CH_GRP_DET();
objGrpDetail.CREATE_DATE = DateTime.Now;
objGrpDetail.LAST_UPD_DATE = DateTime.Now;
objGrpDetail.IS_ACTIVE = "Y";
bc.XREF_CH_GRP_DET_TAG.Add(objGrpDetail);
bc.SaveChanges();
}
}
}
else
{
objGrpDetail.CH_GRP_MST_KEY = channelGrpMstKey;
objGrpDetail.CHANNEL_MST_KEY = channelMstKey;
objGrpDetail.SR_NO = Get_Max_Of_XREF_CH_GRP_DET();
objGrpDetail.CH_GRP_DET_KEY = objGrpDetail.CH_GRP_DET_KEY;
objGrpDetail.CREATE_DATE = DateTime.Now;
objGrpDetail.LAST_UPD_DATE = DateTime.Now;
objGrpDetail.IS_ACTIVE = "Y";
bc.XREF_CH_GRP_DET_TAG.Add(objGrpDetail);
bc.SaveChanges();
}
}
}
}
}
});
TempData["SuccessMsg"] = "Records uploaded Successfully";
return RedirectToAction("CreateChannel");
}
Getting error when generating the primary key value using the below function :
public static decimal Get_Max_Of_XREF_CH_GRP_DET()
{
try
{
BarcDataContext bc = new BarcDataContext();
return bc.XREF_CH_GRP_DET_TAG.Max(m => m.SR_NO) + 1;
}
catch (Exception e)
{
return 1;
}
}
Where SR_NO is the primary key in that table.
Any help will be very much appreciated. Thanks in advance.
The fastest way to do such inserts is using ADO.NET, specifically, SQL Bulk Insert. If you're using SQL Server as your database, the relevant code will be something like this:
DataTable dt = GetDataTableFromExcel(excelFile, true);
using (var copy = new SqlBulkCopy(yourConnectionString) //There are other overloads too
{
BulkCopyTimeout = 10000,
DestinationTableName = dt.TableName,
})
{
foreach (DataColumn column in dt.Columns)
{
copy.ColumnMappings.Add(column.ColumnName, column.ColumnName);
}
copy.WriteToServer(dt);
}
Please look at my comment to other question
You could use guid as primary key into your table. It would help you to avoid problem with ##IDENTITY. At first you should generate new guid-identity, thank insert the generated value into a row
I get a datatable (ora_dt) from an Oracle DB, now i need to add an column(colu_sql) in ora_dt,however i have to get colu_sql's value from some Sqlserver DBs.
Here is my code:
public void ProcessDataTable(DataSet _ds)
{
_ds.Tables[0].Columns.Add(new DataColumn("Descpition", typeof(string)));
int countryId = -1;
string des_ID = string.Empty;
string geo = string.Empty;
foreach (DataRow row in _ds.Tables[0].Rows)
{
if (row["des_ID"] != DBNull.Value)
des_ID = row["des_ID"].ToString();
if (!string.IsNullOrEmpty(des_ID))
{
if (countryId == 12 || countryId == 13)
geo = "NA";
else if ((countryId == 10 || countryId == 11))
geo = "LA";
else
geo = "EMEA";
row["Descpition"] = GetDes(geo, des_ID);
}
else { row["ExemptionDes"] = string.Empty; }
}
}
For every DataRow, inorder to get row["Descpition"] value, i have to check its geo and des_id, and select them from another SqlserverDB.
If the row counts in DataTable is very large, then when i foreach the DataTable, i have to visit the sqlserver db many times, it makes performance bad,
Actually i cannot add new column description in Oracle.how can get high performance when foreach DataRow in a DataTable in my code?
private string GetDes(string geo, string des_ID)
{
string description = string.Empty;
string query = "select description from geo_exemption where des_ID= " + des_ID;
Database DbSQL = DbSQLFactory.CreateDatabase(geo);
using (DataReader dr = DbSQL.ExecuteReader(sqlCmd))
{
while (dr.Read())
{
if (dr["description"] != null)
description = dr["description"].ToString();
}
dr.Close();
}
return description;
}
My suggestion would be getting all the records for description and des_ID from geo_exemption in a single datatable at one go and then using LINQ to filter out the records based on des_ID. In this way you would need to hit the database only once. Rest all the operations will happen on asp.net side.
EDIT:
public void ProcessDataTable(DataSet _ds)
{
if (Session["GeoExpAllRec"] == null)
{
//Fetch all records here and add it to a datatable i.e. "select des_ID, description from geo_exemption"
//Then Add the datatable to the session variable Session["GeoExpAllRec"]
}
_ds.Tables[0].Columns.Add(new DataColumn("Descpition", typeof(string)));
int countryId = -1;
string des_ID = string.Empty;
string geo = string.Empty;
foreach (DataRow row in _ds.Tables[0].Rows)
{
if (row["des_ID"] != DBNull.Value)
des_ID = row["des_ID"].ToString();
if (!string.IsNullOrEmpty(des_ID))
{
if (countryId == 12 || countryId == 13)
geo = "NA";
else if ((countryId == 10 || countryId == 11))
geo = "LA";
else
geo = "EMEA";
//Instead of calling "GetDes" function which will hit the database
//Type-cast the session variable Session["GeoExpAllRec"] to datatable i.e. (Session["GeoExpAllRec"] as DataTable)
//Fire a LINQ query on the datatable to get the desired Description like below
//row["Descpition"] = GetDes(geo, des_ID);
DataTable dt = (Session["GeoExpAllRec"] as DataTable);
row["Descpition"] = dt.AsEnumerable().Where(r => r.Field<string>("des_ID") == des_ID).First()["description"];
}
else { row["ExemptionDes"] = string.Empty; }
}
}
Hope this helps.
I am accessing a database with c#. Now I have to make some calculations with data that I get from some tables and write it into other existing tables. This works quite good in most cases, but for complex operations it takes a huge amount of time. Now I want to know what would be good practice to speed up my querys and get to my results. Here is what I do:
I get a data table that contains 3 values (lom(unique id), laktanfang, laktende) that contains about 700 rows.
For each row in this table I do a query from another table. This results in another data table containing 2 values (lom(unique id), behanddatum)
Now I check if the the value of behanddatum is in between laktanfang and laktende --> yes: Add the row to the data table that gets returned by my function --> no: go on
In the end I have to get the number of positive results from my data table
Here is the code I currently use. I hope it's not too confusing.
public DataTable HoleAbgeschlosseneLaktationenMitDiagnosen(DateTime daAnfang, DateTime daEnde, string[] stDiagnosen = null)
{
DataTable dtRet = new DataTable();
dtRet.Columns.Add("lom", typeof(string));
dtRet.Columns.Add("laktanfang", typeof(DateTime));
dtRet.Columns.Add("laktende", typeof(DateTime));
DataTable dtAbgänge = HoleAbgängeVonEinzeltierZugang(daEnde, daAnfang);
//Abgeschlossene Laktationen für abgegegangene Tiere
foreach (DataRow dr in dtAbgänge.Rows)
{
if (dr != null)
{
DateTime daAbgangsdatum = dr.Field<DateTime>("abgangsdatum");
string stLom = dr.Field<string>("lom");
DataTable dtKalbungVorAbgang = HoleLetzteKalbungFuerTier(stLom, daAbgangsdatum);
if (dtKalbungVorAbgang.Rows.Count > 0 && !dtKalbungVorAbgang.Rows[0].IsNull("kalbedatum"))
{
DateTime daKalbedatum = (DateTime)dtKalbungVorAbgang.Rows[0]["kalbedatum"];
int inLaktation = (int)dtKalbungVorAbgang.Rows[0]["laktation"];
if (PrüfeObDiagnoseInZeitraumAufgetreten(stLom, stDiagnosen, daKalbedatum, daAbgangsdatum) || stDiagnosen == null)
{
DataRow drLaktAbgang = dtRet.NewRow();
drLaktAbgang["lom"] = stLom;
drLaktAbgang["laktanfang"] = daKalbedatum;
drLaktAbgang["laktende"] = daAbgangsdatum;
dtRet.Rows.Add(drLaktAbgang);
}
if (daKalbedatum >= daAnfang && inLaktation > 1)
{
DataTable dtVorherigeKalbung = HoleLetzteKalbungFuerTier(stLom, daKalbedatum.AddDays(-1));
DateTime daVorhKalbung = (DateTime)dtVorherigeKalbung.Rows[0]["kalbedatum"];
if (dtVorherigeKalbung.Rows.Count > 0 && !dtVorherigeKalbung.Rows[0].IsNull("kalbedatum"))
{
if (PrüfeObDiagnoseInZeitraumAufgetreten(stLom, stDiagnosen, daKalbedatum, daAbgangsdatum) || stDiagnosen == null)
{
DataRow drLaktVorhKalbung = dtRet.NewRow();
drLaktVorhKalbung["lom"] = stLom;
drLaktVorhKalbung["laktanfang"] = daVorhKalbung;
drLaktVorhKalbung["laktende"] = daKalbedatum;
dtRet.Rows.Add(drLaktVorhKalbung);
}
}
}
}
}
}
DataTable dtKalbungen = HoleKalbungenFürLebendTiere(daEnde, daAnfang);
//Abgeschlossene Laktationen für lebende Tiere
foreach (DataRow dr in dtKalbungen.Rows)
{
DateTime daKalbedatumLetzte = dr.Field<DateTime>("kalbedatum");
string stLom = dr.Field<string>("lom");
int inLaktation = dr.Field<int>("laktation");
if (inLaktation > 1)
{
DataTable dtKalbungVorErster = HoleLetzteKalbungFuerTier(stLom, daKalbedatumLetzte.AddDays(-1));
if (!dtKalbungVorErster.Rows[0].IsNull("kalbedatum"))
{
DateTime daKalbedatum = (DateTime)dtKalbungVorErster.Rows[0]["kalbedatum"];
if (PrüfeObDiagnoseInZeitraumAufgetreten(stLom, stDiagnosen, daKalbedatum, daKalbedatumLetzte) || stDiagnosen == null)
{
DataRow drLaktKalbung = dtRet.NewRow();
drLaktKalbung["lom"] = stLom;
drLaktKalbung["laktanfang"] = daKalbedatum;
drLaktKalbung["laktende"] = daKalbedatumLetzte;
dtRet.Rows.Add(drLaktKalbung);
}
inLaktation = (int)dtKalbungVorErster.Rows[0]["laktation"];
if (daKalbedatum >= daAnfang && inLaktation > 1)
{
DataTable dtVorherigeKalbung = HoleLetzteKalbungFuerTier(stLom, daKalbedatum.AddDays(-1));
if (dtVorherigeKalbung.Rows.Count > 0 && !dtVorherigeKalbung.Rows[0].IsNull("kalbedatum"))
{
DateTime daVorhKalbung = (DateTime)dtVorherigeKalbung.Rows[0]["kalbedatum"];
if (PrüfeObDiagnoseInZeitraumAufgetreten(stLom, stDiagnosen, daVorhKalbung, daKalbedatum) || stDiagnosen == null)
{
DataRow drLaktVorhKalbung = dtRet.NewRow();
drLaktVorhKalbung["lom"] = stLom;
drLaktVorhKalbung["laktanfang"] = daVorhKalbung;
drLaktVorhKalbung["laktende"] = daKalbedatum;
dtRet.Rows.Add(drLaktVorhKalbung);
}
}
}
}
}
}
return dtRet;
}
private bool PrüfeObDiagnoseInZeitraumAufgetreten(string stLom, string[] stDiagnosen, DateTime daAnfang, DateTime daEnde)
{
SqlCommand cmd = new SqlCommand();
DataTable dtDiagnosenGefunden = new DataTable();
cmd.CommandText = "SELECT diagnose " +
"FROM b_milch_hms_diagnose " +
"WHERE lom=#lom AND behanddatum >= #datumanfang AND behanddatum <= #datumende";
if (stDiagnosen != null)
{
int i = 0;
foreach (string st in stDiagnosen)
{
if (st != "")
{
if (i == 0)
cmd.CommandText += " AND diagnose LIKE #gesuchte_diagnose" + i;
else
cmd.CommandText += " OR diagnose LIKE #gesuchte_diagnose" + i;
cmd.Parameters.AddWithValue("#gesuchte_diagnose" + i, st + "%");
}
i++;
}
}
cmd.Parameters.AddWithValue("#lom", stLom);
cmd.Parameters.AddWithValue("#datumanfang", daAnfang);
cmd.Parameters.AddWithValue("#datumende", daEnde);
dtDiagnosenGefunden = w_milch.FühreSqlAus(cmd);
if (dtDiagnosenGefunden.Rows.Count > 0 && !dtDiagnosenGefunden.Rows[0].IsNull("diagnose"))
return true;
return false;
}
I hope you can help me to improve this function to work more efficient or at least give me some hints.
Thanks in advance
You have created a N+1 problem. One way to solve this would be to change HoleAbgängeVonEinzeltierZugang so that it joins in the data you need from the b_milch_hms_diagnose table.
If you are using .NET 4.0, you can also try to use parallel foreach and see the impact it has on the loop execution time. (This is a more general advice you could apply to many examples)
_dtAbgänge.Rows.AsParallel().ForEach(dr=>
{
//do work
});
I need to modify a dataset before binding it to a gridview.
When I walk through the complete code block, and hover over dsEmployeeOrg, that records
dont appear modified. What am I missing here?
My code is:
DataSet dsEmployeeOrg = eCorporateStaffMgr.GetEmployeeAccessLevel(oEmp);
DataTable dt = dsEmployeeOrg[0];
string sManagerID = "";
string sSupervisorID = "";
string sEmployeeID = "";
for (int i = 0; i < dsEmployeeOrg.Tables[0].Rows.Count; i++)
{
sManagerID = dt.Rows[i].ItemArray[3].ToString().Trim();
sSupervisorID = dt.Rows[i].ItemArray[4].ToString().Trim();
sEmployeeID = dt.Rows[i].ItemArray[5].ToString().Trim();
if ((sManagerID.ToString().Trim() != sSupervisorID.ToString().Trim()) && (sManagerID.ToString().Trim() != sEmployeeID.ToString().Trim()))
{
if (sSupervisorID.ToString().Trim() == sEmployeeID.ToString().Trim())
{
// This is a Supervisor record
dt.Rows[i].ItemArray[2] = "1111";
}
else if (sSupervisorID.ToString().Trim() != sEmployeeID.ToString().Trim())
{
//This is a Employee record
dt.Rows[i].ItemArray[2] = "0000";
}
}
}
Please modify your code as below
DataSet dsEmployeeOrg = eCorporateStaffMgr.GetEmployeeAccessLevel(oEmp);
DataTable dt = dsEmployeeOrg[0];
string sManagerID = "";
string sSupervisorID = "";
string sEmployeeID = "";
for (int i = 0; i < dsEmployeeOrg.Tables[0].Rows.Count; i++)
{
sManagerID = dt.Rows[i].ItemArray[3].ToString().Trim();
sSupervisorID = dt.Rows[i].ItemArray[4].ToString().Trim();
sEmployeeID = dt.Rows[i].ItemArray[5].ToString().Trim();
if ((sManagerID.ToString().Trim() != sSupervisorID.ToString().Trim()) && (sManagerID.ToString().Trim() != sEmployeeID.ToString().Trim()))
{
if (sSupervisorID.ToString().Trim() == sEmployeeID.ToString().Trim())
{
// This is a Supervisor record
dt.Rows[i][2] = "1111";
}
else if (sSupervisorID.ToString().Trim() != sEmployeeID.ToString().Trim())
{
//This is a Employee record
dt.Rows[i][2] = "0000";
}
}
}