C# Load items from file and split into array - c#

HI guys i'm trying to load the contents of my file "item.ids" which currently holds this:
1:Stone
2:Grass
3:Dirt
I want to read each line the the file and split it at the ":". I am using the following code:
foreach(String line in File.ReadAllLines("item.ids")) {
items = line.Split(':');
}
foreach (String part in items)
{
addToList(specs, part);
}
}
public void addToArray(Array array, int index, String s)
{
try
{
array.SetValue(s, index);
}
catch (Exception ex)
{
addToList(specs, ex.ToString());
}
}
public void addToList(ListBox listbox, String s)
{
listbox.Items.Add(s);
}
This works but it only does the last line so it will output it like so:
3
dirt
If you could help me along with my code it would be very helpful.

You need to fill the list after every read.
foreach(String line in File.ReadAllLines("item.ids"))
{
items = line.Split(':');
foreach (String part in items)
{
addToList(specs, part);
}
}
... otherwise you're only ever adding the last item by default.

In the 1st loop you set the item field each time you iterate so when you exit the loop it will be set to the last value. You probably want to change to something like this:
foreach(String line in File.ReadAllLines("item.ids"))
{
foreach (String part in line.Split(':'))
{
addToList(specs, part);
}
}

You've closed your loop to early so items will only contain the last iteration
change your code to:
foreach(String line in File.ReadAllLines("item.ids"))
{
items = line.Split(':');
foreach (String part in items)
{
addToList(specs, part);
}
}

Related

displaying all lines in list box from a file in WPF

I have this code which is suppose to display all lines which contains a specifies string but instead of returning all lines with that string it only returns last line which contains the string. How can I make it to display all lines?
if(bookingType == "Express")
{
string stringToSearch = #"Express";
string[] lines = File.ReadAllLines(#"pathway");
foreach (string line in lines)
{
if (line.Contains(stringToSearch))
{
lstAvailableTrains.Items.Clear();
lstAvailableTrains.Items.Add(line);
}
}
}
You are clearing the items in each time.You need to move clear out of the loop
lstAvailableTrains.Items.Clear();
foreach (string line in lines)
{
if (line.Contains(stringToSearch))
{
lstAvailableTrains.Items.Add(line);
}
}
Use LINQ, and set the ListBox's ItemsSource property:
using System.Linq;
...
lstAvailableTrains.ItemsSource =
File.ReadAllLines("pathway").Where(line => line.Contains(stringToSearch));

Check elements in IEnumerable<string> sequence for specific string

foreach (string s in diff.InSecondNotInFirst)
{
if (!s.Contains("some text"))
{
Assert.Fail();
}
}
Can I do this without the foreach? diff.InSecondNotInFirst is IEnumerable<string>.
With Linq you can do something like:
if (diff.InSecondNotInFirst.Any(s => !s.Contains("some text")))
Assert.Fail();

Unable to remove an item from lsitviewbox

In C# windows application, I am comparing two different string arrays and depending on which array size is big, I add or delete items to a list view box. using the below code I am able to add to list view without any issues, but I am not able to remove from it.
I get an error that says.
"Error CS1503, Argument 1: cannot convert from 'string' to 'System.Windows.Forms.ListViewItem'"
Here is an excerpt from my code
string[] currentFilesList = GetFileList();
if (currentFilesList.Length > prevFilesList.Length)
{
var addedList = currentFilesList.Except(prevFilesList).ToArray();
foreach (var item in addedList)
{
listView1.Items.Add(item);
}
}
if (currentFilesList.Length < prevFilesList.Length)
{
var removedList = prevFilesList.Except(currentFilesList).ToArray();
foreach (string item in removedList)
{
listView1.Items.Remove(item); //I get error here on "item" Argument 1: cannot convert from 'string' to 'System.Windows.Forms.ListViewItem'"
}
}
prevFilesList = currentFilesList;
I tried both string and var but same result.
you can remove item by
foreach (string item in removedList)
{
var toRemove =listView1.Items.Find(item);
if (toRemove != null)
{
listView1.Items.Remove(toRemove);
}
}
or you can use RemoveByKey
foreach (string item in removedList)
{
listView1.Items.RemoveByKey(item);
}
You can try this by using linq
var newlist = listView1.Cast<ListViewItem>().Where(p=>p.Text.Contains("OBJECT")).ToList().ForEach(listBox1.Items.Remove);

Winform: How to Collect All String Values from a ListBox

I'd like to be able to collect all the string values in a Winform ListBox. At the moment my code loops through the ListBox and gets the values, but it's appending all values together in one long string:
private string GetFormNumberValues()
{
string formNumbers = "";
foreach (string item in this.lbFormNumbers.Items)
{
formNumbers += item.ToString();
}
return formNumbers;
}
How can I collect each individual string value to use for later? Thanks.
You can have them in a List this way:
var list = listBox1.Items.Cast<object>().Select(x => x.ToString()).ToList();
Try something like this:
private string[] GetFormNumberValues()
{
List<string> strings = new List<string>();
foreach (string item in this.lbFormNumbers.Items)
{
strings.Add(item.ToString());
}
return strings.ToArray();
}
(Depending on your needs, you could simplify this by returning a List rather than an array...)

how to remove blank spaces from a list when you remove item from a list

I am reading a file in my winform and saving it in a list.i have a button "remove" and on clicking it an item (each list item is a line from the file) from the list is removeed and when i write back this list to a file the items i have removed are replaceed by a blank line.
I don't want these blank lines in my file. can anyone please tell me how to remove them.
I have tried using list.Remove(item) to remove the item from the list.
here is what i have tried...
ListView.CheckedListViewItemCollection chkditems = listView1.CheckedItems;
Regex regex1 = new Regex(".*\"(?<vm_name>.*)\".*:.*{.*\"vmx_path\".*:.*r?\"(?<vmx_path>.*)\",.*\"vm_base\".*:.*r?\"(?<vm_base>.*)\".*");
List<string> list_to_items = new List<string>();
foreach (ListViewItem chkitem in chkditems)
{
foreach (string line in list)
{
Match match1 = regex1.Match(line);
if (match1.Success)
{
if (match1.Groups["vm_name"].Value == chkitem.Text)
{
list_to_items.Add(line);
}
}
}
listView1.Items.Remove(chkitem);
}
foreach (string tormv in index)
{
list.Remove(tormv);
}
for sample data for the list you can consider it containing any text.
Should be a comment, but with code, it's difficult...
I don't know what you're doing, but if you run this code, you'll see that the assumptions of your question are incorrect:
var list = new List<string>{"1","2","3"};
Console.WriteLine(string.Join(", ", list)); // 1, 2, 3
list.Remove("2");
Console.WriteLine(string.Join(", ", list)); // 1, 3

Categories

Resources