Load arraylist into a TextBox - c#

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));

Related

Remove lines from List<String[]> using Linq, if meeting a certain criteria

I've searched around for a solution to this question but can't find an applicable circumstance and can't get my head around it either.
I've got a List<String[]> object (a parsed CSV file) and want to remove any rows if the first value in the row is equal to my criteria.
I've tried the following (with variations) and can't seem to get it to delete the lines, it just passes over them:
rows.RemoveAll(s => s[0].ToString() != "Test");
Which I'm currently reading as, remove s if s[0] (the first value in the row) does not equal "Test".
Can someone point me in the right direction for this?
Thanks, Al.
Edit for wider context / better understanding:
The code is as follows:
private void CleanUpCSV(string path)
{
List<string[]> rows = File.ReadAllLines(path).Select(x => x.Split(',')).ToList();
rows.RemoveAll(s => s[0] != "Test");
using (StreamWriter writer = new StreamWriter(path, false))
{
foreach (var row in rows)
{
writer.WriteLine(row);
}
}
}
So the question is -> Why won't this remove the lines that do not start with "Test" and upon writing, why is it returning System.String[] as all the values?
Did you try with Where? Where is going to filter based on a predicate. You should be able to do something like this:
Demo: Try it online!
List<string[]> rows = new List<string[]> { new []{"Test"}, new []{ "Foo"} };
rows = rows.Where(s => s[0] == "Test").ToList();
foreach(var row in rows)
{
Console.WriteLine(string.Join(",", row));
}
output
Test
You dont need ToString() because S[0] is already a string
You may want to handle empty case or s[0] could throw
You can use s.First() instead of s[0]
You can learn more about Predicateon msdn
Edit
For your example:
private void CleanUpCSV(string path)
{
var rows = File.ReadAllLines(path).Select(x => x.Split(','));
using (StreamWriter writer = new StreamWriter(path, false))
{
foreach (var row in rows.Where(s => s[0] == "Test"))
{
writer.WriteLine(string.Join(",", row));
}
}
}
By the way, you may want to use a library to handle csv parsing. I personally use CsvHelper
The only error in your code is the following:
Since row is string[] this
writer.WriteLine(row);
won't give you the result you were expecting.
Change it like this
writer.WriteLine(String.Join(",", row));
To convert the string[]back into its orginal form.
Any other "optimisation" in all the answers proposed here arent really optimal either.
If you're really trying to remove items where the first element isn't "Test", then your code should work, though you don't need to call .ToString() on s[0] since it's already a string. If this doesn't work for you, perhaps your problem lurks elsewhere? If you give an example of your code in a wider context you could get more help
Filter it like this instead:
var filteredList = rows.Where(s => s[0] == "test").ToArray();

Foreach loop correctly

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

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]});
}

How to add to a list multiple selected values of a ListBox ? C#, ASP.NET web site

I'm working on one of my first projects. I have a listbox where I select multiple values and I would like to add each selection (selectedItem.Text) to a list of strings.
so far what I was working on is something like ..
selectedItem = new List<string>();
var value = lstpdfList.SelectedItem.Text;
for (int i = 0; i < lstpdfList.SelectedValue.Count(); i++)
{
selectedItem.Add(value);
}
I would really appreciate any advice.
Iterate each item from ListBox.Items collection
foreach (ListItem item in ListBox1.Items)
{
if (item.Selected)
{
selectedItem.Add(item.Text); // selectedImte.Add(item.Value);
}
}
There is SelectedItems property of ListBox, try to iterate throught it. For example, if there is strings in your ListBox, then your code might look like this:
selectedItem = new List<string>();
foreach (string value in lstpdfList.SelectedValues)
selectedItem.Add(value);
You can just cast them to strings:
var selectedItems = listBox1.SelectedItems
.Cast<string>()
.ToList();
If you have populated your ListBox with something other than just strings, just cast to whichever type you need, like so:
var selectedItems = listBox1.SelectedItems
.Cast<WhateverYourTypeIs>()
.Select(item => item.ToString())
.ToList();

Display items from a List 10 string items at a time

Hello people I need help please. Here's my code.
In here is a list of strings. Let say there are 100 string in the list.
For now in my code it can display 1 item at a time to a richtextbox using foreach, but I want it to display 10 items at a time.
NOTE: This code is in a foreach statement also. so when th 10 items is displayed it must be clear out before new 10 items comes in again to the richtextbox.
What is your good solution for that?
//foreach (string str in links)
//{
Scanner scanner = new Scanner();
List<string> query = scanner.Parse(parts);
foreach (string item in query)
{
richTextBox6.Invoke((Action)(() => richTextBox6.Text = item));
}
//}
You can use LINQ and use Skip and Take, so Skip(10), Take(10), then you can parse your logic that way.
http://msdn.microsoft.com/en-us/library/bb386988.aspx
Use the AppendText method on the RichTextBox:
Scanner scanner = new Scanner();
List<string> query = scanner.Parse(parts);
foreach (string item in query)
{
richTextBox6.Invoke((Action)(() => richTextBox6.AppendText(item)));
}

Categories