Create more than one row in a for-each loop - c#

Working on an old application I see this code:, It is using DataTable, DataRow stuff.
foreach (string networkIdToCreate in networkIdsToCreate)
{
HTExtractSchema.HTProviderMedicalGroupContractRow rHTProviderMedicalGroupContract = tblHTProviderMedicalGroupContract.NewHTProviderMedicalGroupContractRow();
rHTProviderMedicalGroupContract.ItemArray = rHTProviderMedicalGroupContractDefaults.ItemArray;
rHTProviderMedicalGroupContract.NetworkId = networkIdToCreate;
rHTProviderMedicalGroupContract.Business = "470";
tblHTProviderMedicalGroupContract.Rows.Add(rHTProviderMedicalGroupContract);
}
So it creates the new row, puts some values in there and adds it to the DataTable.
Now I want to modify it to create two rows instead of one row, all values the same except for "Business" field, it is one line before the last in the code above.
So I did that like this:
foreach (string networkIdToCreate in networkIdsToCreate)
{
HTExtractSchema.HTProviderMedicalGroupContractRow rHTProviderMedicalGroupContract = tblHTProviderMedicalGroupContract.NewHTProviderMedicalGroupContractRow();
rHTProviderMedicalGroupContract.ItemArray = rHTProviderMedicalGroupContractDefaults.ItemArray;
rHTProviderMedicalGroupContract.NetworkId = networkIdToCreate;
rHTProviderMedicalGroupContract.Business = "470";
tblHTProviderMedicalGroupContract.Rows.Add(rHTProviderMedicalGroupContract);
HTExtractSchema.HTProviderMedicalGroupContractRow rHTProviderMedicalGroupContract2 = tblHTProviderMedicalGroupContract.NewHTProviderMedicalGroupContractRow();
rHTProviderMedicalGroupContract2.ItemArray = rHTProviderMedicalGroupContractDefaults.ItemArray;
rHTProviderMedicalGroupContract2.NetworkId = networkIdToCreate;
rHTProviderMedicalGroupContract2.Business = "475";
tblHTProviderMedicalGroupContract.Rows.Add(rHTProviderMedicalGroupContract2);
}
But I was wondering if there is a better way other than this copy paste? so if someone saw the code won't laugh at me :D

Just add this internal loop
foreach(var business in new[] {"470", "475"})
{
...
rHTProviderMedicalGroupContract.Business = business ;
...
}
EDIT
Or you can use a method
private void CreatRow(
string networkIdToCreate,
string business)
{
HTExtractSchema.HTProviderMedicalGroupContractRow rHTProviderMedicalGroupContract =
tblHTProviderMedicalGroupContract.NewHTProviderMedicalGroupContractRow();
rHTProviderMedicalGroupContract.ItemArray =
rHTProviderMedicalGroupContractDefaults.ItemArray;
rHTProviderMedicalGroupContract.NetworkId = networkIdToCreate;
rHTProviderMedicalGroupContract.Business = business;
tblHTProviderMedicalGroupContract.Rows.Add(rHTProviderMedicalGroupContract);
}
and use it like this
foreach (string networkIdToCreate in networkIdsToCreate)
{
CreatRow(networkIdToCreate, "470");
CreatRow(networkIdToCreate, "475");
if(networkIdToCreate == "2" || networkIdToCreate == "6")
{
CreateRow(networkIdToCreate, "474");
}
}
Note you may need to pass in tblHTProviderMedicalGroupContract depending on its scope,

Related

SaveChanges problem in N-Tier Architecture

Normally, with MVC I use db.savechanges() method after I do some processes. But check the below code when I use N-Tier Architecture in everyloop its gonna insert in this way but I dont want it. I have to check all the items first. If there is no problem then I have to insert it all together.
foreach (var item in mOrderList)
{
MOrder mOrder = new MOrder();
mOrder.StatusAdmin = false;
mOrder.Date = DateTime.Now;
mOrder.StatusMVendor = "Sipariş alındı.";
mOrder.HowMany = item.HowMany;
mOrder.MBasketId = item.MBasketId;
mOrder.MProductId = item.MProductId;
mOrder.MVendorId = item.MVendorId;
mOrder.WInvestorId = item.WInvestorId;
MProduct mprostock = _imProductService.GetMProductById(item.MProductId);
if (mprostock.Stock<=0)
{
return ReturnErrorAndSuccess(HttpStatusCode.NotFound, "MProduct", mprostock.Name + " ürününde stok kalmadığı için işlem tamamlanamadı.");
}
_imOrderService.InsertMOrder(mOrder);
}
all you have to do is:
first you should define a method that get list of mProductId and then return list of MProduct.
after that you should check if there is any record with Stock<=0 then return your error.
-also for your insert you should define a method that get list of MOrder and return appropriate datatype for example Boolean.
public List<MProduct> GetMProductByIds(List<MProductId> mProductId)
{
//getting record code
}
public bool AddMOrder(List<MOrder> mOrder)
{
//inserting record code
}

Algorithm to implement a JOIN with some limitation

Let me explain my matching problem with a real example (the problem is generic). Assume having 2 lists: of "selections" loaded from different sources. The list don't have duplicates.
Let's say mkTPL.Selections and mkDB.Selections come from SQL Tables each with an unique index on the id and the selection's name. The problem is that sometimes IdSelectionType is null (in the selection from mkTPL.Selections)
foreach (var selTPL in mkTPL.Selections)
{
foreach (var selDB in mkDB.Selections)
{
if (selTPL.IsTheSame(selDB))
selTPL.OddOrResultValue = selDB.OddOrResultValue;
}
}
public bool IsStessaSelezione(SelectionPrints selDb)
{
if (selDb.IdSelectionType == this.IdSelectionType)
return true;
else
{
bool isSameName = selDb.Name == this.Name;
bool isSimilarName = false;
if (!isSameName)
{
isSimilarName = RegexReplace(selDb.Name, #"\([\d.]+\)") == RegexReplace(this.Name, #"\([\d.]+\)");
}
return isSameName || isSimilarName;
}
}
The match alghtoritm that I have implemented is not efficient. Once a selection is matched I shouldn't try to match it further with others (because of the unique index on the id and on the selection name).
Linq could provide me an easy solution?
First of all, you should break when you found a match:
foreach (var selTPL in mkTPL.Selections)
{
foreach (var selDB in mkDB.Selections)
{
if (selTPL.IsTheSame(selDB))
{
selTPL.OddOrResultValue = selDB.OddOrResultValue;
break; // <--
}
}
}
Second, I would make a dictionary of mkDB.Selections, where you store the regexed value so you don't have to make that calculation over and over again, on every iteration.
Something like:
var mkDBDictionary = mkDB.Selections.ToDictionary(s => RegexReplace(s.Name, #"\([\d.]+\)"), s => s);
foreach (var selTPL in mkTPL.Selections)
{
string selTPLName = RegexReplace(selTPL.Name, #"\([\d.]+\)");
if (mkDBDictionary.TryGetValue(selTPLName, out var selDB))
{
selTPL.OddOrResultValue = selDB.OddOrResultValue;
}
}

Iterate through MySql database using C# displaying rows in textbox's foreach or while loop

I'm having a little trouble with my application, I have a Database connected and have already displays the values from the first row in the database, however I need to have the database iterate through each row and display them accordingly replacing what was previously there and ideally being delayed by a timer
I thought this was the correct way of going about it however it doesn't seem right as now it doesn't display anything and gives me a System.NullReferenceException. I have tried to solve the issue but seems to be having no luck. If you could recommend something to read, that would be greatly helpful just can't see a lot on the internet for my specific problem
Any help will be great first time posting on here so sorry if things are in the wrong format.
private void FillInTextFields(DataTable table, int ind)
{
foreach(DataRow dr in table.Rows)
{
foreach(var item in dataRow.ItemArray)
{
dataRow = table.Rows[ind];
txtNHSNumber.Text = dataRow.ItemArray.GetValue(0).ToString();
txtFirstName.Text = dataRow.ItemArray.GetValue(1).ToString();
txtLastName.Text = dataRow.ItemArray.GetValue(2).ToString();
txtTimeDate.Text = dataRow.ItemArray.GetValue(3).ToString();
txtHeartRate.Text = dataRow.ItemArray.GetValue(4).ToString();
txtTemp.Text = dataRow.ItemArray.GetValue(5).ToString();
txtReps.Text = dataRow.ItemArray.GetValue(6).ToString();
txtDia.Text = dataRow.ItemArray.GetValue(7).ToString();
txtSys.Text = dataRow.ItemArray.GetValue(8).ToString();
}
}
}
foreach(var item in dataRow.ItemArray)
should be:
foreach(var item in dr.ItemArray)
can put a sleep at the end of the loop to delay before going back to the top.
It seems you have a few issues. First, your inner loop doesn't seem to be necessary. Second, the outer loop is going through all the rows, even though you're specifically passing the row index into your method. Finally, it seems you're using your "dataRow" variable before it's assigned, although I'd have to see more code to be sure. Consider this:
private void FillInTextFields(DataTable table, int ind)
{
dataRow = table.Rows[ind];
txtNHSNumber.Text = dataRow.ItemArray.GetValue(0).ToString();
txtFirstName.Text = dataRow.ItemArray.GetValue(1).ToString();
txtLastName.Text = dataRow.ItemArray.GetValue(2).ToString();
txtTimeDate.Text = dataRow.ItemArray.GetValue(3).ToString();
txtHeartRate.Text = dataRow.ItemArray.GetValue(4).ToString();
txtTemp.Text = dataRow.ItemArray.GetValue(5).ToString();
txtReps.Text = dataRow.ItemArray.GetValue(6).ToString();
txtDia.Text = dataRow.ItemArray.GetValue(7).ToString();
txtSys.Text = dataRow.ItemArray.GetValue(8).ToString();
}
You'll just need to call this method with the particular index you want to display.
You can also remove the ItemArray.GetValue stuff, and just go with this:
private void FillInTextFields(DataTable table, int ind)
{
dataRow = table.Rows[ind];
txtNHSNumber.Text = dataRow[0].ToString();
txtFirstName.Text = dataRow[1].ToString();
txtLastName.Text = dataRow[2].ToString();
txtTimeDate.Text = dataRow[3].ToString();
txtHeartRate.Text = dataRow[4].ToString();
txtTemp.Text = dataRow[5].ToString();
txtReps.Text = dataRow[6].ToString();
txtDia.Text = dataRow[7].ToString();
txtSys.Text = dataRow[8].ToString();
}
Not sure why you are passing int ind in this method it's not needed.
private void FillInTextFields(DataTable table)
{
txtNHSNumber.Text = table.Rows[0].ItemArray[0];
txtFirstName.Text = table.Rows[0].ItemArray[1];
txtLastName.Text = table.Rows[0].ItemArray[2];
txtTimeDate.Text = table.Rows[0].ItemArray[3];
txtHeartRate.Text = table.Rows[0].ItemArray[4];
txtTemp.Text = table.Rows[0].ItemArray[5];
txtReps.Text = table.Rows[0].ItemArray[6];
txtDia.Text = table.Rows[0].ItemArray[7];
txtSys.Text = table.Rows[0].ItemArray[8];
}

List not populating correctly

Every time I run this code, certlist reads in the first set of values and writes them successfully to the list. When it runs through the loop again the next set of values overwrites the first one and creates a second one. The end result is two identically values inside the list.
Any help with why it would overwrite the first value and how to fix it would be great.
foreach (var certcard in xdoc.Root.Element("Diver").Element("Certifications").Elements("Certification_Card"))
{
cert.Level = certcard.Element("Level").Value;
cert.Agency = certcard.Element("Agency").Value;
cert.Number = certcard.Element("Number").Value;
cert.Date = Convert.ToDateTime(certcard.Element("Date").Value);
certlist.Add(cert);
}
Your original code was only missing the declaration of cert:
foreach (var certcard in xdoc.Root.Element("Diver").Element("Certifications")
.Elements("Certification_Card"))
{
var cert = new Cert();
cert.Level = certcard.Element("Level").Value;
cert.Agency = certcard.Element("Agency").Value;
cert.Number = certcard.Element("Number").Value;
cert.Date = Convert.ToDateTime(certcard.Element("Date").Value);
certlist.Add(cert);
}
Similarly, you could do this without a loop using Linq:
certlist.AddRange(xdoc.Root.Element("Diver")
.Element("Certifications")
.Elements("Certification_Card")
.Select(c => new Cert
{
Level = c.Element("Level").Value,
Agency = c.Element("Agency").Value,
Number = c.Element("Number").Value,
Date = Convert.ToDateTime(c.Element("Date").Value)
}));
Try this :
foreach (var certcard in xdoc.Root.Element("Diver").Element("Certifications")
.Elements("Certification_Card"))
{
certlist.Add(new Cert()
{
Level = certcard.Element("Level").Value,
Agency = certcard.Element("Agency").Value,
Number = certcard.Element("Number").Value,
Date = Convert.ToDateTime(certcard.Element("Date").Value)
});
}

How to copy value of one data column into another data column in the same data table C#?

I want to copy itemarray[4] of datatable to itemarray[6] of that datatable. I used this code and I didn’t see any changes:
foreach (DataRow dr_row in dt_table.Rows)
{
foreach (var field_value in dr_row.ItemArray)
{
object cell_data = field_value;
if (dr_row.ItemArray[6].ToString() == "")
{
dr_row.ItemArray[6] = dr_row.ItemArray[4];
}
original_data += cell_data.ToString();
}
original_data += Environment.NewLine;
}
First of all never do this:
dr_row.ItemArray[6].ToString() == ""
Change it to this:
dr_row.ItemArray[6].ToString() == String.Empty
or:
String.IsNullOrEmpty(dr_row.ItemArray[6].ToString())
However, that is just good practice. Now, to the problem that you are facing.
What the Itemarray does is, it creates a new array from the row, so that if you change the array, you do not change the row.
Do this:
dr_row[6] = dr_row[4];
Should work.
Try this,
foreach (DataRow dr_row in dt_table.Rows)
{
dr_row[6] = dr_row[4];
}
and use System.Text.StringBuilder to append data.
System.Text.StringBuilder sb = new StringBuilder();
sb.Append(value1);

Categories

Resources