Foreach loop correctly - c#

I have a data table and i'm trying to loop through the rows and create a zipCode array. This issue that i'm only getting one number 4 times. I know I'm doin something wrong but can somebody point this out to me and give and explanation.
Thanks
public string bindMap()
{
using (dal.Sys.RegionTableAdapters.region_countyListTa ta = new Cea.WebApp.JobsEq.Dal.Sys.RegionTableAdapters.region_countyListTa())
{
List<string> code = new List<string>();
dal.Sys.Region.region_countyListDataTable dt = ta.GetData(region.RegionType, region.RegionCode);
foreach (var row in dt)
{
code.Add(region.ZipCode);
}//end foreach loop
string codes = string.Join(",", code.ToArray());
return codes.ToString();
}//end for each loop
}//end bind map

You aren't using the variable that you are iterating with.
foreach (var row in dt)
{
//Not sure how you will get ZipCode from the ROW, but you get the idea.
code.Add(row["ZipCode"]);
}//end foreach loop

As a general desc of the row/cell value, I use this general (NOTE: GENERAL) block:
foreach(var item : items) {
//before adding there is maybe some casting or other work...
listName.add(item["FieldName"]);
}
Understandable is that the listName is of type fieldNameType

Related

How to search for similar string in DataTable

I want to be able to detect 2 similar strings in my datatable. How do I do that?
foreach (DataRow row2 in visualDataTable.Rows)
{
foreach (char server in serverName)
{
foreach(similar string in servername)
{
// do something..
}
}
}
The simplest approach would involve iterating two times through your rows and compare each value with one and another (similar to your above approach):
foreach (DataRow row in visualDataTable.Rows)
{
foreach (DataRow compareRow in visualDataTable.Rows))
{
if(row["<your column>"] == compareRow["<your column>"])
{
// The two rows have the same column value for <your column>
// Do something
}
}
}

I need to use a for-loop to find strings in an array-list that have the same word in them

I need to find a way to use a for-loop to find how many strings that are the same word in the same array-list. I need to use the for-loop because everytime it loops and finds another word that is the same I want to add it to an int variable :the following is the code that have tried to use but it didn;t work. variable bedrooms kept saying that it is 0 when it is not
foreach (string row in RoomType) // RoomType is the ArrayList
{
if (row.Equals("Bedroom"))
{
bedrooms++;
}
}
This code works, which is based on your code. I am assuming that you are probably doing something in your code where bedrooms is getting re-declared during the looping. This is a guess though.
var RoomType = new ArrayList();
var bedrooms = 0;
RoomType.Add("workflow");
RoomType.Add("Bedroom");
RoomType.Add("Bedroom");
foreach (string row in RoomType) // RoomType is the ArrayList
{
if (row.Equals("Bedroom"))
{
bedrooms++;
}
}
Console.WriteLine(bedrooms);
A different way:
var row = RoomType.Cast<string>().ToArray();
var count = row.Aggregate(0, (c, i) => (i.Equals("Bedroom")) ? ++c : c);
If you are not compelled to use a loop, you could try starting with this:
int bedrooms = RoomType.ToArray().Count(row => row.Equals("Bedroom"));
If you are compelled to use a loop, then please post a bit more of the code so that we can see where and how these objects are being set.

How to retrieve all viewstate lists

I'm saving Viewstates like this with several students:
ViewState[currentStudent] = currentGradesList;
But now i need to take all the viewstates to get the average of all grades, i've learnt to do it with strings like so:
foreach (string str in ViewState.Keys) {....} and that works.
But now when i try
foreach(List<double> grades in ViewState.Keys) {....}
the "grades" remain null and i get the error:
Unable to cast object of type 'System.String' to type 'System.Collections.Generic.List`1[System.Double]'.
I guess it says that Keys are strings, but how would i then get all the lists??
You are looping through the names of the keys in your foreach loop, not the actual values. You use the value of the foreach loop variable (which is now the name of a key in your ViewState dictionary) to go get the value from the viewstate.
Change your foreach loop to something like this
foreach(var key in ViewState.keys)[
var grades = ViewState[key] as List<double>;
//LINQ has built in Average and Sum abilities on lists
//I don't know what a CurrentStudentGrades looks like
//but here is an example of using the built in average
var studentAverage = grades.Average(x=>x.Grade);
//do whatever else you are wanting to do
}
foreach (string str in ViewState.Keys)
{
var grades = ViewState[str] as List<double>;
if(grades != null)
{
var average = grades.Average();
}
}
Solution:
I was looping through the names of the viewstate keys, not the values. So now i changed it to
Foreach (string str in ViewState.Keys)
{ //And then the value of "str"...
List<double> templist = (List<double>)ViewState[str];
And then the rest of my code which doesn't matter really but here it is to get average grade of each student, and all students together
foreach (double grade in templist)
{
currenttotal += grade;
}
currentaverage = currenttotal / templist.count;
AllAveragesList.add(currentaverage)
foreach (double average in AllAveragesList)
{
totalOfAll += average
}
averageOfAll = totalOfAll / AllAveragesList.count();`

DataGridView: Add new row using an array or List<t>

I've two listbox-elements in my form.
The items in listbox1 are representing the columns in my DataGridView,
the items in my listbox2 are representing the rows in my DataGridView.
foreach (var el in listBox1Elements)
{
// code...
dataGridView1.Columns.Add(col);
}
Since items in listbox1 can be added or deleted I've a problem with my current solution.
dataGridView1.Rows.Add("test","some","data","even","more","data");
I wonder if there is a solution for using a List.
Then my code could look something like this:
foreach (var el in listBox2Elements)
{
myList.add("some text");
}
dataGridView1.Rows.Add(myList);
Something like
foreach (var el in listBox2Elements)
myList.add("some text");
foreach (var item in myList)
dataGridView1.Rows.Add(item.., item.., item..);
or
dataGridView1.DataSource = myList.ToList()
How about:
foreach (var el in listBox2Elements)
{
myList.add("some text");
}
dataGridView1.Rows.Add(myList.ToArray());
well thats some hard task to do without a store object.
there you could easily go:
//Not taking guarantee for this approach
Store.DataSource.add(new object[]{"some text"});
Store.DataBind();
or you define a new Data source object and fill it with the list items (via loop) and do that again after doing:
(list<string>) data_list.add("some text");
//repopulate data object and set a Store.DataSource;
Store.dataBind();
and for deleting objects you would delete them from the list<string> item and update the store like above
//population for the data object:
for(int x=0; x<= data_list.length(); x++)
{
data.add(new object[]{data_list[x]});
}

Load arraylist into a TextBox

I have another question and I can't seem to find anything on Google.
What this program does
This program displays the information from an RSS feed.
Question
How can I load all the items from an Arraylist to a TextBox?
Things I have tried
This is what I have so far:
List<Array> list1 = new List<Array>();
foreach (var item in list1)
{
textBox1.AppendText(item.ToString());
}
Problem
When I do this, the TextBox shows this:
System.String[]System.String[]
Instead of:
Recommended Build for CraftBukkit: 1.2.4-R1.0 (build 2126)
http://dl.bukkit.org/downloads/craftbukkit/view/00993_1.2.4-R1.0/
Does anybody have any idea how this array stuff work?
Do I need to loop through the array and search for specific indexes?
Sorry, but I'm still a little bit new to C#, and sorry for my English I'm Dutch :<.
It looks like you ArrayList contains array of string instead of string. So try this :
foreach (var item in list1.OfType<string[]>().SelectMany(i => i))
{
textBox1.AppendText(item);
}
It seems that item is a string array, so try to implode it:
foreach (var item in list1)
{
textBox1.AppendText(string.Join("", item));
}
Your code is basically a list of array. That's why it is showing system.string[]
Change it to
foreach (var item in list1)
{
textBox1.AppendText(string.Join("", item));
}
It will join your each string[] (i.e. item) in List<> and create it like
firstarrrayfirstitem, firstarrayseconditem
and textbox as
firstarrrayfirstitem, firstarrayseconditem, secondarrayfirstitem, secondarrayseconditem.... and so on.
A better way could be to use a stringbuider for better performance and reduction in a propertychanged event called by the textbox;
System.Text.StringBuilder sb = new System.Text.StringBuilder();
foreach (var item in list1.OfType<string[]>().SelectMany(i => i))
{
sb.Append(item);
}
textBox1.Text = sb.ToString();
Better way:
textBox1.Text = string.Join("", list1.OfType<string[]>().SelectMany(i => i));

Categories