How to get all rows in two foreach? - c#

I don't know how to get the first rows of a first foreach run with the first rows of a second foreach.
The second rows of a first foreach run with the second rows of the second foreach.
Because I get all data into List<> and the foreach two list.
My code like:
for (int i = valuesFrom; i < valuesTo; i++)
{
values = name + " " + i;
lstAliasImage.Add(values);
}
for (int j = 0; j < lstImgAdded.Items.Count; j++)
{
string imgPath = lstImgAdded.Items[j].Text;
lstNameImage.Add(imgPath);
}
foreach (var alias in lstAliasImage)
{
foreach (var items in lstNameImage)
{
txtUser.Text = alisa;
Save(items + " " + txtUser.Text);
}
}

You can do that with a good old for cycle:
for (int i = 0; i < lstAliasImage.Count; i++) {
txtUser.Text = listAliasImage.ElementAt(i);
Save(lstNameImage.ElementAt(i) + " " + txtUser.Text);
}
Here I assumed that by alisa you meant alias. Also, I assumed that the element count is the same. If your type has an indexer defined, then you can use [i] instead of ElementAt(i).

Using a for loop will solve your problem;
for (int i = 0; i < lstAliasImage.Count; i++)
{
txtUser.Text = lstAliasImage[i];
Save(lstNameImage[i] + " " + txtUser.Text);
}
But it is better to solve this in a different way. As both Lists are related, you should create a struct, and store that in the list. At least to avoid errors if both lists are not the same length. Something like
public struct ImageStruct
{
public String alias;
public String name;
}
List<ImageStruct> images = new List<ImageStruct>();
for (int i = valuesFrom; i < valuesTo; i++)
{
images.Add(new ImageStruct()
{
alias="alias " + i,
name="name " + i
});
}
foreach (var item in images)
{
txtUser.Text = item.alias;
Save(item.name + " " + item.alias);
}
I hope you get the idea (I did not test the above code).

Related

c# I have a very confusing InvalidCastException error

I'm having an error that says "invalid cast exception" whenever I try to open one specific form in a program i'm making. The code here takes data from text files to put it into a data grid view. It also makes calculations to put averages in the data grid view. I'm getting an error that seems to involve a variable called "skiTime", which is an average of 3 other variables: "skiTime1" "skiTime2" and "skiTime3". The numbers are decimals, e.g. 23.22, or 54.32, etc.
When I try to load this form, the program closes and Visual studio highlights this line:
decimal skiTimeDecimal = Convert.ToDecimal(skiTime[i]);
I don't know what part of the code the error is in, it could literally be anywhere since my code is so messy, I basically just pulled from random tutorials, and answers to questions I asked here because I need it done for school and don't know c#. Here's the full part of the code that I think might relate to this error.
using (StreamWriter sw = new StreamWriter("groups.txt", false))
{
for (int i = 0; i < skiTimeID.Count; i++)
{
for (int j = 0; j < quizID.Count; j++)
{
for (int l = 0; l < pupilDetailsID.Count; l++)
{
if (skiTimeID[i] == quizID[j] && quizID[j] == pupilDetailsID[l])
{
string fullPupilRecord = pupilDetailsID[l] + "~" + pupilDetailsFirstName[l] + "~" + pupilDetailsSurname[l] + "~" + pupilDetailsClass[l]
+ "~" + pupilDetailsNumber[l] + "~" + skiTime[i] + "~" + quizScore[j] + "~" + quizPercentage[j];
int quizScoreNumber = Convert.ToInt32(quizScore[j]);
decimal skiTimeDecimal = Convert.ToDecimal(skiTime[i]);
if (quizScoreNumber >= 3 && skiTimeDecimal <= 40)
{
groupLevel = "Advanced";
}
else if (quizScoreNumber >= 2 && skiTimeDecimal <= 50)
{
groupLevel = "Intermediate";
}
else
{
groupLevel = "Beginner";
}
fullPupilRecord = fullPupilRecord + "~" + groupLevel;
sw.WriteLine(fullPupilRecord);
fullPupilRecord = "";
}
}
}
}
If it helps, here is the code that finds the average between the variables for skiTime:
public string CalculateAverage(List<string> skiTime1, List<string> skiTime2, List<string> skiTime3)
{
List<string> allValues = new List<string>();
allValues.AddRange(skiTime1);
allValues.AddRange(skiTime2);
allValues.AddRange(skiTime3);
decimal totalcount = 0;
decimal average = 0;
foreach (var value in allValues)
{
totalcount = totalcount + decimal.Parse(value);
}
average = totalcount / allValues.Count();
return average.ToString();
}

can a string array go past 111?

I am trying to make an array that will gather all the lines in all the files in a directory, I thought I had it finally, but when the string array gets to entry 111 it crashes with an IndexOutOfRangeException
string[] WordList = new string[AdjectiveListLength];
Console.WriteLine("Length .. " + AdjectiveListLength);
Console.WriteLine("String Length .. " + WordList.Length);
int o = 0;
for (int i = 0; i < FileEntries.Length; i++)
{
WordList = File.ReadAllLines(FileEntries[i]);
foreach (string s in WordList)
{
Console.WriteLine(s + " .. " + i + " .. " + o);
WordList[o] = s;
//o += 1;
}
}
The exception points to the int I commented out when I get the error, I've been trying to get this for a few hours and I've finally gotten this far I feel like I'm 1 inch from the finish line but I can't figure out what's going on.
The best way for this task is to use a List<string> that could be used without knowing beforehand the length of each file in your FileEntries array
List<string> WordList = null;
for (int i = 0; i < FileEntries.Length; i++)
{
WordList = File.ReadLines(FileEntries[i]).ToList();
foreach (string s in WordList)
Console.WriteLine(s + " .. " + i);
// If you want also the line number then you could just use normal for..loop and C# 6.0 syntax
for(int o = 0; o < WordList.Count(); o++)
Console.WriteLine($"File:{i} at line {o} is ..{WordList[o]}");
}
If you really want to use arrays then you don't need to dimension the array because File.ReadAllLines already creates the array for you
string[] WordList = null;
for (int i = 0; i < FileEntries.Length; i++)
{
WordList = File.ReadAllLines(FileEntries[i]);
foreach (string s in WordList)
Console.WriteLine(s + " .. " + i);
}

How can I remove the values apostrophes of my choice from a line?

I want to remove in each line from specific values the apostrophes.
This is my code for writing into a text file:
for (int a = 0; a < checkedListBox1.CheckedItems.Count; a++)
{
DataTable ExportTable = new DataTable();
//Debug.WriteLine(checkedListBox1.CheckedItems[a].ToString());
string SelectLines =
"SELECT Identifier,
TestID,
Description,
Enabled,
StringLimit,
LowLimit,
HighLimit,
LimitType,
Unit,
Parameters
FROM specifications
where Identifier = '" + checkedListBox1.CheckedItems[a] + "'";
ExportTable = ObjSqlAccess.GetDataTableFromTable(SelectLines);
int rowcount = ExportTable.Rows.Count;
int columncount = ExportTable.Columns.Count;
int rw = 0;
int clm = 0;
writeText.WriteLine("\r\n\r\n[" + checkedListBox1.CheckedItems[a].ToString() + "]" + "\r\nCount = " + (rowcount - 1));
for (rw = 0; rw < rowcount - 1; rw++)
{
string test = "";
for (clm = 0; clm < columncount - 1; clm++)
{
test += ExportTable.Rows[rw][clm].ToString();
test += "','";
}
writeText.WriteLine((rw + 1) + "=(Identifier,TestID,Description,Enabled,StringLimit,LowLimit,HighLimit,LimitType,Unit,Parameters) VALUES ('" + removeThis + "')");
}
writeText.Flush();
writeText.Close();
writeText.Dispose();
And for instance, I want to remove the apostrophes from each line from only these values: 1, 0 , 0 before writing it to a text file. Or to be more specific, only the values that are assigned to Enable, LowLimit and HighLimit column.
Does anyone has an idea of how to proceed? I hope my question is clear enough.
Try this:
for (clm = 0; clm < columncount - 1; clm++)
{
DataColumn col = ExportTable.Columns[clm];
test += ExportTable.Rows[rw][clm].ToString();
if (col.DataType == bool || col.DataType == Int32) //Add other types that dont require single quotes to if statement
{
test += ",";
}
else
{
test += "','";
}
}
First, I would change the way you're writing the string so it doesn't care if there are single quotes, or anything else, in the variable you pass for VALUES.
writeText.WriteLine((rw + 1) + "=(Identifier,TestID,Description,Enabled,StringLimit,LowLimit,HighLimit,LimitType,Unit,Parameters) VALUES (" + test + ")");
Also worth noting is I don't think your loops will work correctly. When you use a count in a for loop, the count is already 1-indexed. So, if you do columnCount = ExportTable.Columns.Count;, your loop should be for (int i = 0; i < columnCount; i++). An easy way to remember is index is 0-based, but count is 1-based.
I would also use a string builder instead. Then in your loop just do a check for those columns:
string test = "";
for (clm = 0; clm < columncount; clm++)
{
StringBuilder sb = new Stringbuilder();
sb.Append(ExportTable.Rows[rw][clm].ToString());
if (clm != 3 && clm != 5 && clm != 6)
{
sb.Insert(0,"'");
sb.Append("'");
}
test += sb;
if (clm != columncount - 1) // add a comma if it's not the last column
{
test += ",";
}
}

Why datatable ignores initial spaces

Datatable does not take initial spaces, so when i insert it into database and retrieve it by select statement and display it on page using stringBuilder, Initial spaces are gone and text does not appear on screen as it is written in textbox
DataTable1.Rows[0][0]=TextBox1.Text;
This is how I insert into database
public static void Insert(DataTable table)
{
StringBuilder Col = new StringBuilder();
StringBuilder Val = new StringBuilder();
string Query, finalVal;
int i, j;
int count = 0;
int ColumnCount = table.Columns.Count;
for (i = 0; i < ColumnCount; i++)
{
if (table.Rows.OfType<DataRow>().Any(r => !r.IsNull(table.Columns[i].ColumnName)))
{
Col.Append(table.Columns[i].ColumnName);
Col.Append(",");
count++;
}
}
Col.Remove(Col.Length - 1, 1);
string[] columnName = Col.ToString().Split(',');
foreach (DataRow r in table.Rows)
{
Val.Append(",(");
for (j = 0; j < count; j++)
{
if (r[columnName[j]] != null)
{
Val.Append("'" + r[columnName[j]] + "'");
Val.Append(",");
}
else
{
Val.Append("null,");
}
}
Val.Append(")");
Val.Remove(Val.Length - 2, 1);
}
finalVal = Val.ToString().Substring(1);
Query = "Insert into " + table.TableName + "(" + Col + ")" + "Values" + finalVal;
EduDB.ExecuteNonQuery(Query);
}
You must be trimming the string befor inserting into database. Please check that out

Error in string.join while creating a multi dimensional array

I have created a multi-dimensional array:
string[,] array_questions = new string[dt.Rows.Count, dt.Columns.Count];
for (i = 0; i < dt.Rows.Count; i++)
{
for (j = 0; j < dt.Columns.Count; j++)
{
array_questions[i, j] = dt.Rows[i][j].ToString();
//Response.Write(array_questions[i, j]);
}
// Response.Write(Environment.NewLine);
//Response.Write("\n");
}
foreach (string number in array_questions)
{
//Response.Write(number + " ");
//Response.Write(Environment.NewLine);
Response.Write(string.Join(", ", number) + Environment.NewLine);
}
but it shows an error like : Error 1 The best overloaded method match for 'string.Join(string, string[])' has some invalid arguments.. Please help
You do not need a for loop to join the string.
string.Join(", ", array_questions)
Replace the code
foreach (string number in array_questions)
{
//Response.Write(number + " ");
//Response.Write(Environment.NewLine);
Response.Write(string.Join(", ", number) + Environment.NewLine);
}
with
Response.Write(string.Join(", ", array_questions) + Environment.NewLine);
You need to flatten your array to use string.Join. It takes the separator and a single dimensional array, so you may proabably need to do something like this. But not sure what you are trying to achieve here. You are trying to call string.Join(string, string[]) as string.Join(string, string)
Try something like this:
var sdArray= new List<string>();
for (var i = 0; i < dt.Rows.Count; i++) //Get the length of first Dimension
{
for (var j = 0; j < dt.Columns.Count; j++) //Get the length of second Dimension
{
sdArray.Add(array_questions[i, j]);
}
}
///
Response.Write(string.Join(", ", sdArray) + Environment.NewLine);
Using Linq you can flatten this in a better way.
Something like this
string joinedSetOfQns= string.Join(",",
Enumerable.Range(0, dt.Rows.Count)
.SelectMany(i => Enumerable.Range(0, dt.Columns.Count)
.Select(j => array_questions[i, j])));
Response.Write(joinedSetOfQns + Environment.NewLine);
This is the defenision for string.Join
public static string Join(
string separator,
params string[] value /// <-- Takes single Dimensional Array not a string.
)
Update: Since you need to join Rowwise
for (var i = 0; i < dt.Rows.Count; i++)
{
var result = new List<string>();
for (var j = 0; j < dt.Columns.Count; j++)
{
result.Add(array_questions[i, j]);
}
Response.Write(string.Join(", ", result) + Environment.NewLine);
}

Categories

Resources