I am using a data table to store some data. After the for loop check the length of the data table, the data table clears itself. There is no data in it. Can you advise why is it so ? This is part part of a report that is using the DevExpress reporting engine to create the reports.
DataTable ResultList = new DataTable();
ResultList.Columns.Add("range");
ResultList.Columns.Add("bpfrom");
ResultList.Columns.Add("bpto");
ResultList.Columns.Add("qualMemb");
ResultList.Columns.Add("qualTurn");
ResultList.Columns.Add("qualTurnPercent");
ResultList.Columns.Add("grMemb");
ResultList.Columns.Add("grTurn");
ResultList.Columns.Add("grTurnPercent");
ResultList.Columns.Add("totalamt");
ResultList.Columns.Add("giftlevel");
string[] fromrangelist = fromrange.Split(',');
string[] torangelist = torange.Split(',');
int j;
if (fromrange == "")
{
DataRow dr = ResultList.NewRow();
dr["range"] = 1;
dr["bpfrom"] = 0;
dr["bpto"] = 100000000; //biggest value
dr["giftlevel"] = "ALL";
ResultList.Rows.Add(dr);
}
else
{
for (j = 0; j < fromrangelist.Length; j++)
{
DataRow dr = ResultList.NewRow();
dr["range"] = j + 1;
dr["bpfrom"] = Convert.ToDecimal(fromrangelist[j]);
dr["bpto"] = Convert.ToDecimal(torangelist[j]);
dr["giftlevel"] = "level:" + (j + 1).ToString() + "(" + fromrangelist[j] + "-" + torangelist[j] + ")";
ResultList.Rows.Add(dr);
}
}
//Get ALL Total spend
decimal TotalSpend = Math.Round((from table1 in context.mmsspddtls
where table1.mmsspdcpcd.Equals(cpcd) && table1.mmsspdbrcd.Equals(brcd)
&& table1.mmsspdtxdt >= fromtxdate && table1.mmsspdtxdt <= totxdate
&& (table1.mmsspdtxty.Equals(null) || table1.mmsspdtxty.Equals("") || table1.mmsspdtxty.Equals("PS") || table1.mmsspdtxty.Equals("PE") || table1.mmsspdtxty.Equals("PR"))
&& (table1.mmsspdplna.Equals('1') || table1.mmsspdplna.Equals('5') || table1.mmsspdplna.Equals('P') || table1.mmsspdplna.Equals('T') || table1.mmsspdplna.Equals('A') || table1.mmsspdplna.Equals('L'))
&& !table1.mmsspdstfg.Equals('V')
select new
{
totalamt = table1.mmsspdpram
}).Sum(s => s.totalamt), 2);
for (int i = 0; i < ResultList.Rows.Count; i++)
{
decimal fromvalue = Convert.ToDecimal(ResultList.Rows[i]["bpfrom"]);
decimal tovalue = Convert.ToDecimal(ResultList.Rows[i]["bpto"]);
ResultList.Rows[i]["totalamt"] = TotalSpend;
//Member Query that match the range
var MemberQuery = (from table1 in context.mmscrdlogs
where table1.mmscdlcpcd.Equals(cpcd) && table1.mmscdlbrcd.Equals(brcd)
&& table1.mmscdlstst.Equals('N') && table1.mmscdlbpis >= fromvalue && table1.mmscdlbpis <= tovalue
&& table1.mmscdleddt >= fromexpiredate && table1.mmscdleddt <= toexpiredate
select new
{
spendfr = fromvalue,
spendto = tovalue,
membercode = table1.mmscdlmbcd
}).Distinct();
//Count of member in the range
ResultList.Rows[i]["qualMemb"] = MemberQuery.Count();
//member total spend in the range
decimal qualTurn = 0;
var qualQuery = (from table1 in context.mmsspddtls
from table2 in MemberQuery.Where(s => s.membercode == table1.mmsspdmbcd)
where table1.mmsspdcpcd.Equals(cpcd) && table1.mmsspdbrcd.Equals(brcd)
&& table1.mmsspdtxdt >= fromtxdate && table1.mmsspdtxdt <= totxdate
&& (table1.mmsspdtxty.Equals(null) || table1.mmsspdtxty.Equals("") || table1.mmsspdtxty.Equals("PS") || table1.mmsspdtxty.Equals("PE") || table1.mmsspdtxty.Equals("PR"))
&& (table1.mmsspdplna.Equals('1') || table1.mmsspdplna.Equals('5') || table1.mmsspdplna.Equals('P') || table1.mmsspdplna.Equals('T') || table1.mmsspdplna.Equals('A') || table1.mmsspdplna.Equals('L'))
&& !table1.mmsspdstfg.Equals('V')
select new
{
totalamt = table1.mmsspdpram
});
if(qualQuery.Count() > 0)
{
qualTurn = Math.Round(qualQuery.Sum(s => s.totalamt), 2);
}
ResultList.Rows[i]["qualTurn"] = qualTurn;
//member total spend% with total in the range
if (qualTurn == 0)
ResultList.Rows[i]["qualTurnPercent"] = 0;
else
ResultList.Rows[i]["qualTurnPercent"] = Math.Round((qualTurn / TotalSpend) * 100, 2);
var MemberQueryGR = (from table1 in context.mmsspddtls
from table2 in context.pxppludpxes.Where(s => s.pxppdxcpcd.Equals(table1.mmsspdcpcd) && s.pxppdxbrcd.Equals(table1.mmsspdbrcd) && s.pxppdxplcd.Equals(table1.mmsspdplcd))
from table3 in context.mmssyspars.Where(s => s.mmssypcpcd.Equals(table1.mmsspdcpcd) && s.mmssypbrcd.Equals(table1.mmsspdbrcd))
where table1.mmsspdcpcd.Equals(cpcd) && table1.mmsspdbrcd.Equals(brcd)
&& table2.pxppdxpx01 / (table3.mmssypbpmt / table3.mmssyppont) >= fromvalue
&& table2.pxppdxpx01 / (table3.mmssypbpmt / table3.mmssyppont) <= tovalue
&& table1.mmsspdtxty.Equals("GR") && table1.mmsspdplna.Equals('2')
&& table1.mmsspdtxdt >= fromtxdate && table1.mmsspdtxdt <= totxdate
select new
{
spendfr = fromvalue,
spendto = tovalue,
membercode = table1.mmsspdmbcd
}).Distinct();
//Count of GR member in the range
ResultList.Rows[i]["grMemb"] = MemberQueryGR.Count();
//GR member total spend in the range
decimal grTurn = 0;
if (MemberQueryGR.Count() > 0)
{
var grQuery = (from table1 in context.mmsspddtls
from table2 in MemberQueryGR.Where(s => s.membercode == table1.mmsspdmbcd)
where table1.mmsspdcpcd.Equals(cpcd) && table1.mmsspdbrcd.Equals(brcd)
&& table1.mmsspdtxdt >= fromtxdate && table1.mmsspdtxdt <= totxdate
&& (table1.mmsspdtxty.Equals(null) || table1.mmsspdtxty.Equals("") || table1.mmsspdtxty.Equals("PS") || table1.mmsspdtxty.Equals("PE") || table1.mmsspdtxty.Equals("PR"))
&& (table1.mmsspdplna.Equals('1') || table1.mmsspdplna.Equals('5') || table1.mmsspdplna.Equals('P') || table1.mmsspdplna.Equals('T') || table1.mmsspdplna.Equals('A') || table1.mmsspdplna.Equals('L'))
&& !table1.mmsspdstfg.Equals('V')
select new
{
totalamt = table1.mmsspdpram
});
if(grQuery.Count() > 0)
{
grTurn = Math.Round(grQuery.Sum(s => s.totalamt), 2);
}
}
ResultList.Rows[i]["grTurn"] = grTurn;
//member total spend% with total in the range
if (grTurn == 0)
ResultList.Rows[i]["grTurnPercent"] = 0;
else
ResultList.Rows[i]["grTurnPercent"] = Math.Round((grTurn / TotalSpend) * 100, 2);
}
DataSource = ResultList;
}
Please advise. Thanks
Related
This question already has an answer here:
Arrays in visual basic Creating a program that deals with driving distance [closed]
(1 answer)
Closed 4 years ago.
So the issue is
"Create a project that looks up the driving distance between two cities. Use two drop-down lists that contain the names of the cities. Label one list Departure and the other Destination. Use a Look Up button to calculate the distance.
Store the distances in a two-dimensional table."
is there a better way of coding this by using a for loop
ok here is the code below
private void lookUpButton_Click(object sender, EventArgs e)
{
int [,] miles = { {0,1004, 1753, 2752, 3017,1520, 1507,609, 3115,448},
{1004,0, 921,1780, 2048, 1397, 919,515 , 2176,709},
{ 1753,921, 0,1230, 1399,1343, 517,1435, 2234,1307},
{ 2752,1780,1230,0 , 272,2570, 1732,2251, 1322,2420},
{3017,2048 , 1399,272, 0,2716, 1858,2523, 1278,2646},
{ 1520,1397, 1343,2570, 2716,0, 860,1494, 3447,1057},
{ 1507,919, 517,1732, 1858,860, 0,1307, 2734,1099},
{ 609,515, 1435,2251, 2523,1494, 1307,0, 2820,571},
{ 3155,2176, 2234,1322, 1278,3447, 2734,2820, 0,2887},
{ 448,709, 1307,2420, 2646,1057, 1099,571,2887,0 }
};
//var distance = miles[txtDeparture.SelectedIndex,txtDeparture.SelectedIndex];
// alot of if statments
if ((txtDeparture.SelectedIndex == 0) && (txtDestination.SelectedIndex == 0))
{
var distance = miles[0, 0];
txtDistancebox.Text = distance.ToString();
}
else if ((txtDeparture.SelectedIndex == 0) && (txtDestination.SelectedIndex == 1))
{
var distance = miles[0, 1];
txtDistancebox.Text = distance.ToString();
}
else if ((txtDeparture.SelectedIndex == 0) && (txtDestination.SelectedIndex == 2))
{
var distance = miles[0, 2];
txtDistancebox.Text = distance.ToString();
}
else if ((txtDeparture.SelectedIndex == 0) && (txtDestination.SelectedIndex == 3))
{
var distance = miles[0, 3];
txtDistancebox.Text = distance.ToString();
}
else if ((txtDeparture.SelectedIndex == 0) && (txtDestination.SelectedIndex == 4))
{
var distance = miles[0, 4];
txtDistancebox.Text = distance.ToString();
}
else if ((txtDeparture.SelectedIndex == 0) && (txtDestination.SelectedIndex == 5))
{
var distance = miles[0, 5];
txtDistancebox.Text = distance.ToString();
}
else if ((txtDeparture.SelectedIndex == 0) && (txtDestination.SelectedIndex == 6))
{
var distance = miles[0, 6];
txtDistancebox.Text = distance.ToString();
}
else if ((txtDeparture.SelectedIndex == 0) && (txtDestination.SelectedIndex == 7))
{
var distance = miles[0, 7];
txtDistancebox.Text = distance.ToString();
}
else if ((txtDeparture.SelectedIndex == 0) && (txtDestination.SelectedIndex == 8))
{
var distance = miles[0, 8];
txtDistancebox.Text = distance.ToString();
}
else if ((txtDeparture.SelectedIndex == 0) && (txtDestination.SelectedIndex == 9))
{
var distance = miles[0, 9];
txtDistancebox.Text = distance.ToString();
}
else if ((txtDeparture.SelectedIndex == 0) && (txtDestination.SelectedIndex == 10))
{
var distance = miles[0, 10];
txtDistancebox.Text = distance.ToString();
}
else if ((txtDeparture.SelectedIndex == 1) && (txtDestination.SelectedIndex == 0))
{
var distance = miles[1, 0];
txtDistancebox.Text = distance.ToString();
}
}
Something like this:
var distance = miles[txtDeparture.SelectedIndex, txtDestination.SelectedIndex];
txtDistancebox.Text = distance.ToString();
I think you can make one method for calculating txtDistancebox.
like as ...Private int CalculateDistace(int DepartureIndex, int DestinationIndex)
I have a data from database in a DaTaTable Object and i am performing a row calculation based on some formula defined in a list of string but unfortunately i am ending up with wrong calculation because Sequence of rows value does not match with given formula so calculations going wrong
For e.x ( Income before pipeline, depr/amort and MSR )= Net Production Income - Total Personal Cost - Other Cost + Service Fee Income
For that in a loop first value is coming from datatable is Total Personal Cost and second is Other Cost third is Service Fee Income and in last Net Production Income. which form this formula
Income before pipeline, depr/amort and MSR = Total Personal Cost - Other Cost + Service Fee Income + Net Production income.
Please give me a solution and in that particular below code this code is performing row calculation for given formula
for (int P = 0; P < dt.Rows.Count; P++)
{
rowName = dt.Rows[P]["GLDescription"].ToString();
AddColume[0] = "";
if (AddColume.Contains(rowName))
{
int l = 1;
var DRValue = dt.Rows[P][j];
if (!(DRValue == null || DRValue == DBNull.Value))
{
if (Expression[index] == "+")
{
totalRow += Convert.ToDecimal(DRValue);
}
else if (Expression[index] == "-")
{
totalRow -= Convert.ToDecimal(DRValue);
}
index++;
}
}
else if (AddColume.Contains(rowName) && AddColume.Contains("self"))
{
var DRValue = dt.Rows[P][j];
if (!(DRValue == null || DRValue == DBNull.Value))
{
decimal CurrentValue = Convert.ToDecimal(DRValue);
dt.Rows[P][j] = CurrentValue * -1;
}
}
}
for you support i have this code
List<string> lstGrouping = new List<string>();
lstGrouping.Add("Volume↔Volume↔Volume↔Sigular");
lstGrouping.Add("Units↔Units↔Units↔Sigular");
lstGrouping.Add("Blank↔Blank↔Sigular");
lstGrouping.Add("Total Production Revenue↔Secondary-Net (Sell - Buy +/- Hedge)↔Branch Brokered Loan Income↔add");
lstGrouping.Add("Total Direct Costs↔Deed Recording↔Provisions for Loan Losses↔add");
lstGrouping.Add("Net Production Income↔Total Production Revenue↔Total Direct Costs↔+$-");
lstGrouping.Add("Total Personnel Costs↔Accounting Dept↔Employer payroll tax exp↔add");
lstGrouping.Add("Total G&A Costs and Other↔Bank Fees↔Provisions for Branch Losses↔add");
lstGrouping.Add("Servicing Fee Income↔Servicing Fee Income , net of expenses↔Servicing Fee Income , net of expenses↔Sigular");
lstGrouping.Add("Income before pipeline, depr/amort and MSR↔Net Production Income↔Total Personnel Costs↔Total G&A Costs and Other↔Servicing Fee Income↔+$+$-$-");
lstGrouping.Add("Other items Total↔Servicing Fee Income , net of expenses↔Depreciation Expense↔add");
lstGrouping.Add("Net Income↔Income before pipeline, depr/amort and MSR↔Other items Total↔+$+");
for (int i = 0; i < lstGrouping.Count; i++)
{
var AddColume = lstGrouping[i].Split('↔');
var Expression = AddColume[(AddColume.Length) - 1].Split('$');
int startindex = 0;
int Endindex = 0;
foreach (DataRow DR in dt.Rows)
{
string GlDescription = DR["GLDescription"].ToString();
if (GlDescription.Trim() == AddColume[1].Trim())
startindex = dt.Rows.IndexOf(DR);
else if (GlDescription.Trim() == AddColume[2].Trim())
Endindex = dt.Rows.IndexOf(DR);
}
DataRow NewDR = dt.NewRow();
if (Expression[0] == "add")
dt.Rows.InsertAt(NewDR, Endindex + 1);
else if (Expression[0] == "Sigular")
{
Endindex = 1;
}
else
dt.Rows.Add(NewDR);
DataRow level1Row = dtLevel1.NewRow();
dtLevel1.Rows.Add(level1Row);
if (startindex != null && Endindex != null)
{
for (int j = 0; j < dt.Columns.Count; j++)
{
string ColName = dt.Columns[j].ColumnName;
if (ColName != "GLDescription" && ColName != "GLDescriptionId")
{
decimal totalRow = 0;
if (Expression[0] == "add")
{
for (int K = startindex; K <= Endindex; K++)
{
var DRValue = dt.Rows[K][j];
if (DRValue == null || DRValue == DBNull.Value)
DRValue = 0;
if (Expression[0].Contains("add"))
totalRow += Convert.ToDecimal(DRValue);
}
}
else if (Expression[0] == "Sigular")
{
int KeyValue = startindex;
var DRValue = dt.Rows[KeyValue][j];
if (DRValue == null || DRValue == DBNull.Value)
DRValue = 0;
totalRow += Convert.ToDecimal(DRValue);
}
else
{
int index = 0;
int paraindex = 0;
string rowName;
for (int P = 0; P < dt.Rows.Count; P++)
{
rowName = dt.Rows[P]["GLDescription"].ToString();
AddColume[0] = "";
if (AddColume.Contains(rowName))
{
int l = 1;
var DRValue = dt.Rows[P][j];
if (!(DRValue == null || DRValue == DBNull.Value))
{
if (Expression[index] == "+")
{
totalRow += Convert.ToDecimal(DRValue);
}
else if (Expression[index] == "-")
{
totalRow -= Convert.ToDecimal(DRValue);
}
index++;
}
}
else if (AddColume.Contains(rowName) && AddColume.Contains("self"))
{
var DRValue = dt.Rows[P][j];
if (!(DRValue == null || DRValue == DBNull.Value))
{
decimal CurrentValue = Convert.ToDecimal(DRValue);
dt.Rows[P][j] = CurrentValue * -1;
}
}
}
}
NewDR[ColName] = totalRow;
level1Row[ColName] = totalRow;
}
else if (ColName == "GLDescription")
{
NewDR[ColName] = AddColume[0];
level1Row[ColName] = AddColume[0];
}
}
}
}
dtLevel2 = dt;
if (level == "lev1")
return dtLevel1;
else if (level == "lev2")
return dt;
else
return null;
I am querying for report module to show a pivot table, some of the columns are dynamic, so i am creating a dictionary object to construct my object, so let say i have 1 user_applications table with around 40k records, and this table also referenced by other tables.
i do this :
//masters
var master_genders = CTX.translate_value_ms.Where(a => a.PSF_type == "SEX").OrderBy(o => o.translate_value_id).ToList();
var master_edus = CTX.education_lvl_ms.OrderBy(o => o.education_lvl_id).ToList();
var master_stats = CTX.app_status_ms.OrderBy(o => o.status_order).ToList();
var master_criteria = CTX.criteria_suggestion_templates.OrderBy(o => o.criteria_suggestion_template_id).ToList();
//
//load mapping
Dictionary<int, int> Gender_Map = new Dictionary<int, int>();
int start = 0;
foreach (var m in master_genders)
{
Gender_Map.Add(m.translate_value_id, start);
start++;
}
Dictionary<int, int> Edu_Map = new Dictionary<int, int>();
start = 0;
foreach (var e in master_edus)
{
Edu_Map.Add(e.education_lvl_id, start);
start++;
}
Dictionary<string, int> Stat_Map = new Dictionary<string, int>();
start = 0;
var first = master_stats.GroupBy(g => g.status_web).OrderBy(o => o.FirstOrDefault().status_order);
foreach (var s in first)
{
Stat_Map.Add(s.Key, start);
start++;
}
Dictionary<int, int> Criteria_Map = new Dictionary<int, int>();
start = 0;
foreach (var m in master_criteria)
{
Criteria_Map.Add(m.criteria_suggestion_template_id, start);
start++;
}
//
var idx = 0;
var cur_age = 0;
int int_jobfair = 0;
int total = 0;
user_address address_dom = null;
string key = "";
bool check = false;
ReportSubObject obj = null;
user_edu user_last_edu = null;
user_test last_test = null;
criteria_suggestion checkcrit = null;
var usertest = CTX.user_tests;
var testcriteria = CTX.criteria_suggestions;
double total_a = 0;
double total_b = 0;
double total_c = 0;
double total_d = 0;
double total_e = 0;
double total_f = 0;
var addresses = CTX.user_addresses.Where(a => a.address_type == 0).ToList();
foreach (var itm in apps.ToList())
{
var a_begin = DateTime.Now;
total = 0;
address_dom = null;
key = "";
check = false;
obj = null;
user_last_edu = null;
last_test = null;
checkcrit = null;
address_dom = addresses.Where(a => a.user_id == itm.user_id).FirstOrDefault();
var a_end = DateTime.Now;
DateTime b_begin = DateTime.Now;
DateTime b_end = DateTime.Now;
DateTime c_begin = DateTime.Now;
DateTime c_end = DateTime.Now;
DateTime d_begin = DateTime.Now;
DateTime d_end = DateTime.Now;
DateTime e_begin = DateTime.Now;
DateTime e_end = DateTime.Now;
DateTime f_begin = DateTime.Now;
DateTime f_end = DateTime.Now;
b_begin = DateTime.Now;
int_jobfair = 0;
if (itm.manager_id != null)
int_jobfair = 1;
key = int_jobfair + " - " + itm.applied_date.Value.Month + " - " + itm.posting.job_id + " - " + itm.posting.location_id + " - " + itm.posting.job_cat_id + " - " + itm.posting.office_cat_id + " - " + (address_dom != null && address_dom.state_id != null ? address_dom.state_id.ToString() : "0");
check = SubmissionObj.ContainsKey(key);
if (!check)
{
obj = new ReportSubObject();
obj.Source = (itm.manager_id != null ? "Job Fair" : "Website");
obj.Job = myTI.ToTitleCase(itm.posting.job_m.PSF_Desc.ToLower());
obj.Location = myTI.ToTitleCase(itm.posting.job_location_m.PSF_Desc.ToLower());
obj.JobCat = myTI.ToTitleCase(itm.posting.job_category_m.PSF_Desc.ToLower());
obj.OfficeCat = myTI.ToTitleCase(itm.posting.office_category_m.PSF_Desc.ToLower());
obj.ApplyProv = (address_dom != null && address_dom.state_id != null ? address_dom.state_m.state_desc : "");
obj.from = (DateTime)itm.applied_date;
obj.Total = total += 1;
#region gender
obj.KeyPairGender = new List<int>();
master_genders.ForEach(b => obj.KeyPairGender.Add(0));
if (itm.user_list.gender_id != null)
{
idx = Gender_Map[(int)itm.user_list.gender_id];
//obj.KeyPairGender[idx] = new KeyValuePair<string, int>(obj.KeyPairGender[idx].Key, obj.KeyPairGender[idx].Value + 1);
obj.KeyPairGender[idx] += 1;
}
#endregion
#region edu
obj.KeyPairEdu = new List<int>();
master_edus.ForEach(b => obj.KeyPairEdu.Add(0));
user_last_edu = itm.user_list.user_edus.OrderByDescending(o => o.edu_lvl_id).FirstOrDefault();
if (user_last_edu != null)
{
idx = Edu_Map[(int)user_last_edu.edu_lvl_id];
obj.KeyPairEdu[idx] += 1;
}
#endregion
b_end = DateTime.Now;
c_begin = DateTime.Now;
#region Age
obj.AgeRange = new int[5];
for (int i = 0; i < 5; i++)
{
obj.AgeRange[i] = 0;
}
cur_age = itm.applied_date.Value.Year - itm.user_list.birthday.Value.Year;
if (itm.user_list.birthday > ((DateTime)itm.applied_date).AddYears(-cur_age)) cur_age--;
if (cur_age >= 18 && cur_age <= 21)
obj.AgeRange[0] += 1;
else if (cur_age >= 22 && cur_age <= 24)
obj.AgeRange[1] += 1;
else if (cur_age >= 25 && cur_age <= 27)
obj.AgeRange[2] += 1;
else if (cur_age >= 28 && cur_age <= 30)
obj.AgeRange[3] += 1;
else if (cur_age > 30)
obj.AgeRange[4] += 1;
#endregion
#region appstatus
obj.KeyPairAppStat = new List<int>();
foreach (var loop in first)
{
obj.KeyPairAppStat.Add(0);
}
if (itm.app_status_id != null)
{
idx = Stat_Map[itm.app_status_m.status_web];
obj.KeyPairAppStat[idx] += 1;
}
#endregion
#region criteria
obj.KeyPairCriteria = new List<int>();
master_criteria.ForEach(b => obj.KeyPairCriteria.Add(0));
if (itm.online_test_id != null)
{
last_test = usertest.Where(a => a.user_id == itm.user_id && a.package_id == itm.online_test.package_id).OrderByDescending(o => o.date_score).FirstOrDefault();
if (last_test != null)
{
if (last_test.total_score != null)
{
checkcrit = testcriteria.Where(a => a.package_id == last_test.package_id &&
(last_test.total_score >= a.score_from && last_test.total_score <= a.score_to)
).FirstOrDefault();
if (checkcrit != null)
{
idx = Criteria_Map[(int)checkcrit.criteria_opt_id];
obj.KeyPairCriteria[idx] += 1;
}
}
}
}
#endregion
SubmissionObj.Add(key, obj);
c_end = DateTime.Now;
}
else
{
d_begin = DateTime.Now;
var tmp = SubmissionObj[key];
tmp.Total++;
if (tmp.to < itm.applied_date)
tmp.to = (DateTime)itm.applied_date;
#region gender
if (itm.user_list.gender_id != null)
{
idx = Gender_Map[(int)itm.user_list.gender_id];
tmp.KeyPairGender[idx] += 1;
}
#endregion
d_end = DateTime.Now;
e_begin = DateTime.Now;
#region edu
user_last_edu = itm.user_list.user_edus.OrderByDescending(o => o.edu_lvl_id).FirstOrDefault();
if (user_last_edu != null)
{
idx = Edu_Map[(int)user_last_edu.edu_lvl_id];
tmp.KeyPairEdu[idx] += 1;
}
#endregion
#region age
cur_age = itm.applied_date.Value.Year - itm.user_list.birthday.Value.Year;
if (itm.user_list.birthday > ((DateTime)itm.applied_date).AddYears(-cur_age)) cur_age--;
if (cur_age >= 18 && cur_age <= 21)
tmp.AgeRange[0] += 1;
else if (cur_age >= 22 && cur_age <= 24)
tmp.AgeRange[1] += 1;
else if (cur_age >= 25 && cur_age <= 27)
tmp.AgeRange[2] += 1;
else if (cur_age >= 28 && cur_age <= 30)
tmp.AgeRange[3] += 1;
else if (cur_age > 30)
tmp.AgeRange[4] += 1;
#endregion
#region appstatus
if (itm.app_status_id != null)
{
idx = Stat_Map[itm.app_status_m.status_web];
tmp.KeyPairAppStat[idx] += 1;
}
#endregion
e_end = DateTime.Now;
f_begin = DateTime.Now;
#region criteria
if (itm.online_test_id != null)
{
last_test = usertest.Where(a => a.user_id == itm.user_id && a.package_id == itm.online_test.package_id).OrderByDescending(o => o.date_score).FirstOrDefault();
if (last_test != null)
{
if (last_test.date_score != null)
{
checkcrit = testcriteria.Where(a => a.package_id == last_test.package_id &&
(last_test.total_score >= a.score_from && last_test.total_score <= a.score_to)
).FirstOrDefault();
if (checkcrit != null)
{
idx = Criteria_Map[(int)checkcrit.criteria_opt_id];
tmp.KeyPairCriteria[idx] += 1;
}
}
}
}
#endregion
f_end = DateTime.Now;
}
total_a += (a_end - a_begin).TotalSeconds;
total_b += (b_end - b_begin).TotalSeconds;
total_c += (c_end - c_begin).TotalSeconds;
total_d += (d_end - d_begin).TotalSeconds;
total_e += (e_end - e_begin).TotalSeconds;
total_f += (f_end - f_begin).TotalSeconds;
}
as u notice in above code, i have a few sub queries inside foreach loop, and i put a few variables to count which part took most time in seconds, and its true that the sub queries part took the longest, overall it took around 2 minutes for those codes to be executed, so i tried to move all sub queries outside foreach loop, i do this :
var customapp = apps.Select(x => new
{
dom_address = x.user_list.user_addresses.Where(a => a.address_type == 0).FirstOrDefault(),
manager_id = x.manager_id,
applied_date = x.applied_date,
job_id = x.posting.job_id,
job_desc = x.posting.job_m.PSF_Desc,
location_id = x.posting.location_id,
loc_desc = x.posting.job_location_m.PSF_Desc,
job_cat_id = x.posting.job_cat_id,
job_cat_desc = x.posting.job_category_m.PSF_Desc,
office_cat_id = x.posting.office_cat_id,
office_cat_desc = x.posting.office_category_m.PSF_Desc,
gender_id = x.user_list.gender_id,
birthday = x.user_list.birthday,
edu = x.user_list.user_edus.OrderByDescending(o => o.edu_lvl_id).FirstOrDefault(),
status_PSF_id = x.app_status_id,
status_from_PSF = x.app_status_m.status_web,
online_test_id = x.online_test_id,
last_test = x.user_tests.Where(a => a.user_id == x.user_id && a.package_id == x.online_test.package_id).OrderByDescending(o => o.date_score).FirstOrDefault()
});
DateTime end_z = DateTime.Now;
double total_z = (end_z - begin_z).TotalSeconds;
foreach (var itm in customapp.ToList())
{
//logic to construct my dictionary as before, but without sub queries.
}
the second code it does not improve the speed, instead it took longer than previous one, can u tell me what can i do to optimize my query?
The problem is that you are doing extra db calls for each subquery for each application.
This is how you can avoid it:
// Plain query, not doing subqueries. Unfortunately brings extra rows in memory.
var q =
from app in ctx.Applications
join s in ctx.SubObjectsOne on app.Id equals s.AppId into joinedSubObjectOne
from subObjectOne in joinedSubObjectOne.DefaultIfEmpty()
where subObjectOne.SomeProperty == 0 // additional sub object criteria
select new { app, subObjectOne };
var l = q.ToList();
// From now on objects are materialized, doing the rest in memory:
var translated =
from i in l
group i by i.app.Id into g
select new
{
app = g.First().app,
// This is expensive too, but not doing separate db requests.
SubObjectOneByMaxProperty = g.Select(i => i.subObjectOne).OrderByDescending(s => s.SomeOrder).FirstOrDefault()
};
var translatedList = translated.ToList();
You can use this approach if your sub-object counts are not very high.
If you can figure out how to compute a needed value using sql aggregates, it would be even better. For example,
subObjects.Where(..).OrderByDescencing(..).First(..) would turn into subObjects.Max(s=>s.SomeProp), if you need just a max value, not an entire object. It would compute directly in db without extra db calls.
And an even better approach would be to avoid computations at the time of building a report. You can denormalize your data slightly, for example - store the ids of needed objects in an aggregation table, and update the table when related data changes:
table aggregated_data(app_id, address_id, max_edu_lvl_id, max_score_test_id)
I have strings like:
1) Cookie:ystat_tw_ss376223=9_16940400_234398;
2) Cookie:zynga_toolbar_fb_uid=1018132522
3) GET /2009/visuels/Metaboli_120x600_UK.gif HTTP/1.1
4) GET /2010/07/15/ipad-3hk-smv-price-hk/ HTTP/1.1
1 ad 2 have common substtring{cookie:}
3 and 4 have common substtring{GET /20, HTTP/1.1}
I want to find all common substrings that have the length more than three characters(contain space character) between 2 strings.(like 1 and 2)
i want to code in c#. i have a program but it has some problems.
Could anyone help me?
public static string[] MyMCS2(string a, string b)
{
string[] st = new string[100];
// List<string> st = new List<string>();
List<char> f = new List<char>();
int ctr = 0;
char[] str1 = a.ToCharArray();
char[] str2 = b.ToCharArray();
int m = 0;
int n = 0;
while (m < str1.Length)
{
for (n = 0; n < str2.Length; n++)
{
if (m < str1.Length)
{
if (str1[m] == str2[n])
{
if ((m > 1) && (n > 1) &&(str1[m - 1] == str2[n - 1]) && (str1[m - 2] == str2[n - 2]))
{
//f[m]= str1[m];
f.Add(str1[m]);
char[] ff = f.ToArray();
string aaa = new string(ff);
if (aaa.Length >= 3)
{
st[ctr] = aaa + "()";
//st.Add(aaa);
ctr++;
}
kk = m;
m++;
}
else if ((n == 0) ||(n == 1))
{
f.Add(str1[m]);
kk = m;
m++;
}
else
f.Clear();
}
//else if ((str1[m] == str2[n]) && (m == str1.Length - 1) && (n == str2.Length - 1))
//{
// f.Add(str1[m]);
// char[] ff = f.ToArray();
// string aaa = new string(ff);
// if (aaa.Length >= 3)
// {
// st[ctr] = aaa;
// ctr++;
// }
// // m++;
//}
else if ((str1[m] != str2[n]) && (n == (str2.Length - 1)))
{
m++;
}
else if ((m > 1) && (n > 1) && (str1[m] != str2[n]) && (str1[m - 1] == str2[n - 1]) && (str1[m - 2] == str2[n - 2]) && (str1[m - 3] == str2[n - 3]))
{
//
char[] ff = f.ToArray();
string aaa = new string(ff);
if (aaa.Length >= 3)
{
st[ctr] = aaa + "()" ;
//st.Add(aaa);
ctr++;
f.Clear();
}
//f.Clear();
//for (int h = 0; h < ff.Length; h++)
//{
// f[h] = '\0';
//}
}
else if (str1[m] != str2[n])
continue;
}
}
}
//int gb = st.Length;
return st;
}
This is an exact matching problem not a substring. You can solve it with aho-corasick algorithm. Use the first string and compute a finite state machine. Then process the search string. You can extend the aho-corasick algorithm to use a wildcard and search also for substrings. You can try this animated example: http://blog.ivank.net/aho-corasick-algorithm-in-as3.html
i have code that its working but its not as i would like.
in runtime i create many new textbox/labels so i had to use 10 ifs to check each "future" textbox have textlength = 0 and != null
i would like to use repeat structure like for or while, dont know if its possible.
For example, if i create more textbox/labels will be impossible have really big code.
See my code:
private void cadeiaapagarcampos(TextBox _text, EventArgs e)
{
if (_text.Text == "")
{
Label lblAcessorio2 = (Label)gpbCategoria.Controls.Find("lblAcessorio2", false).FirstOrDefault();
TextBox txtAcessorio2 = (TextBox)gpbCategoria.Controls.Find("txtAcessorio2", false).FirstOrDefault();
Label lblAcessorio3 = (Label)gpbCategoria.Controls.Find("lblAcessorio3", false).FirstOrDefault();
TextBox txtAcessorio3 = (TextBox)gpbCategoria.Controls.Find("txtAcessorio3", false).FirstOrDefault();
Label lblAcessorio4 = (Label)gpbCategoria.Controls.Find("lblAcessorio4", false).FirstOrDefault();
TextBox txtAcessorio4 = (TextBox)gpbCategoria.Controls.Find("txtAcessorio4", false).FirstOrDefault();
Label lblAcessorio5 = (Label)gpbCategoria.Controls.Find("lblAcessorio5", false).FirstOrDefault();
TextBox txtAcessorio5 = (TextBox)gpbCategoria.Controls.Find("txtAcessorio5", false).FirstOrDefault();
Label lblAcessorio6 = (Label)gpbCategoria.Controls.Find("lblAcessorio6", false).FirstOrDefault();
TextBox txtAcessorio6 = (TextBox)gpbCategoria.Controls.Find("txtAcessorio6", false).FirstOrDefault();
Label lblAcessorio7 = (Label)gpbCategoria.Controls.Find("lblAcessorio7", false).FirstOrDefault();
TextBox txtAcessorio7 = (TextBox)gpbCategoria.Controls.Find("txtAcessorio7", false).FirstOrDefault();
Label lblAcessorio8 = (Label)gpbCategoria.Controls.Find("lblAcessorio8", false).FirstOrDefault();
TextBox txtAcessorio8 = (TextBox)gpbCategoria.Controls.Find("txtAcessorio8", false).FirstOrDefault();
Label lblAcessorio9 = (Label)gpbCategoria.Controls.Find("lblAcessorio9", false).FirstOrDefault();
TextBox txtAcessorio9 = (TextBox)gpbCategoria.Controls.Find("txtAcessorio9", false).FirstOrDefault();
Label lblAcessorio10 = (Label)gpbCategoria.Controls.Find("lblAcessorio10", false).FirstOrDefault();
TextBox txtAcessorio10 = (TextBox)gpbCategoria.Controls.Find("txtAcessorio10", false).FirstOrDefault();
if (txtAcessorio2 != null && txtAcessorio2.TextLength == 0)
{
gpbCategoria.Controls.Remove(txtAcessorio2);
gpbCategoria.Controls.Remove(lblAcessorio2);
btnSalvar.Focus();
if (test != 1)
{
n--;
t++;
if (n >= 1 && n <= 10)
{
testeapagar();
test = 1;
}
}
}
if (txtAcessorio3 != null && txtAcessorio3.TextLength == 0)
{
gpbCategoria.Controls.Remove(txtAcessorio3);
gpbCategoria.Controls.Remove(lblAcessorio3);
btnSalvar.Focus();
if (test != 1)
{
n--;
t++;
if (n >= 1 && n <= 10)
{
testeapagar();
test = 1;
}
}
}
if (txtAcessorio4 != null && txtAcessorio4.TextLength == 0)
{
gpbCategoria.Controls.Remove(txtAcessorio4);
gpbCategoria.Controls.Remove(lblAcessorio4);
btnSalvar.Focus();
if (test != 1)
{
n--;
t++;
if (n >= 1 && n <= 10)
{
testeapagar();
test = 1;
}
}
}
if (txtAcessorio5 != null && txtAcessorio5.TextLength == 0)
{
gpbCategoria.Controls.Remove(txtAcessorio5);
gpbCategoria.Controls.Remove(lblAcessorio5);
btnSalvar.Focus();
if (test != 1)
{
n--;
t++;
if (n >= 1 && n <= 10)
{
testeapagar();
test = 1;
}
}
}
if (txtAcessorio6 != null && txtAcessorio6.TextLength == 0)
{
gpbCategoria.Controls.Remove(txtAcessorio6);
gpbCategoria.Controls.Remove(lblAcessorio6);
btnSalvar.Focus();
if (test != 1)
{
n--;
t++;
if (n >= 1 && n <= 10)
{
testeapagar();
test = 1;
}
}
}
if (txtAcessorio7 != null && txtAcessorio7.TextLength == 0)
{
gpbCategoria.Controls.Remove(txtAcessorio7);
gpbCategoria.Controls.Remove(lblAcessorio7);
btnSalvar.Focus();
if (test != 1)
{
n--;
t++;
if (n >= 1 && n <= 10)
{
testeapagar();
test = 1;
}
}
}
if (txtAcessorio8 != null && txtAcessorio8.TextLength == 0)
{
gpbCategoria.Controls.Remove(txtAcessorio8);
gpbCategoria.Controls.Remove(lblAcessorio8);
btnSalvar.Focus();
if (test != 1)
{
n--;
t++;
if (n >= 1 && n <= 10)
{
testeapagar();
test = 1;
}
}
}
if (txtAcessorio9 != null && txtAcessorio9.TextLength == 0)
{
gpbCategoria.Controls.Remove(txtAcessorio9);
gpbCategoria.Controls.Remove(lblAcessorio9);
btnSalvar.Focus();
if (test != 1)
{
n--;
t++;
if (n >= 1 && n <= 10)
{
testeapagar();
test = 1;
}
}
}
}
}
Would something like this be what you are looking for? If you have more labels just update iAcessorioContar and it will automatically check them as well as long as you name the labels incrementally.
private void cadeiaapagarcampos(TextBox _text, EventArgs e)
{
if (_text.Text == "")
{
int iAcessorioContar = 10;
for (int iContador = 2; iContador <= iAcessorioContar; iContador++) {
Label lblAcessorio = (Label)gpbCategoria.Controls.Find("lblAcessorio"+iContador, false).FirstOrDefault();
TextBox txtAcessorio = (TextBox)gpbCategoria.Controls.Find("txtAcessorio"+iContador, false).FirstOrDefault();
if (txtAcessorio != null && txtAcessorio.TextLength == 0)
{
gpbCategoria.Controls.Remove(txtAcessorio);
gpbCategoria.Controls.Remove(lblAcessorio);
btnSalvar.Focus();
if (test != 1) {
n--;
t++;
if (n >= 1 && n <= 10)
{
testeapagar();
test = 1;
}
}
}
}
}
}
You could add the controls in pairs (label and textbox) to a list when you create them so you do not have to search the controls collection which can cost a lot of time.
You can then simply loop the list.