I have multiple foreach loops through which i am fetching the work history , education history of the users from Facebook and inserting these into a database:
Result soap = serializer.Deserialize<Result>(ser);
foreach (var item in soap.data)
{
int length = item.education_history.Length;
int lenght2 = item.work_history.Length;
foreach (var edu in item.education_history)
{
length--;
ftr = ftr + "," + edu.name.ToString();
}
foreach (var wrk in item.work_history)
{
lenght2--;
ftr1 = ftr1 + "," + wrk.company_name.ToString();
}
string str1 = "Insert into [Snaps] (Loc_city,Loc_state,Loc_country,Edu_Hist1,Work_Hist1) values ('" + item.current_location.city.ToString() + "','" + item.current_location.state.ToString() + "','" + item.current_location.country.ToString() + "','" + ftr + "','" + ftr1 + "')";
SqlCommand cmd1 = new SqlCommand(str1, con);
cmd1.ExecuteNonQuery();
}
PS: This code is just for testing purposes thus not used parameterized sql query
The problem i am encountering is that when i am calculating the values of ftr and ftr1 of the first item in the parent foreach loop
foreach (var item in soap.data)
and when i insert these values into the database it appends the second array index in item and saves it in the database. Also the values of ftr and ftr1 are not getting refreshed it appends the new values with the previous ones
What am i doing wrong here?
Thanks
The problem is that the
ftrandftr1variables are not being reset after each iteration in the main loop, hence the values keep being concatenated to them.One solution would be to set both
ftrandftr1tonullor empty strings at the end of the main loop:However, a simpler approach would be to use the Enumerable.Select method in LINQ to extract the lists of values from the
education_historyandwork_historyarrays and use String.Join to concatenate them into two strings:This way the
ftrandftr1variables are declared at each iteration, so there’s no need to manually reset their value.