List and foreach

I seem to have a very strange problem, and I really don't know what is going on. This is the source code I'm trying to debug.

StorageFile file = await roamingFolder.GetFileAsync(filename); string text = await FileIO.ReadTextAsync(file); string[] shows = text.Split(new[] { ":?;" }, StringSplitOptions.None); List<show> showslist = new List<show>(); foreach (string splitshow in shows) { string[] show1 = splitshow.Split(new[] { ",?;" }, StringSplitOptions.None); episode = show1[0]; name = show1[1]; showslist.Add(new show { name = name, episode = episode }); } Output.ItemsSource = showslist; 

It is strange that the list is shown only if I put Output.ItemsSource = showslist; inside the foreach loop, but not when it is outside, and I really don’t understand why it is not. I mean, the list items are already added to it, right?

We tried many different methods, and most of them, even if they displayed the list data, had many different problems that were too messy to fix.

Anyway, appreciate any hint or help, thanks.

+6
source share
1 answer

I bet your data is not entirely correct. I think one of the last / last entries throws an exception and is swallowed higher in your code (or not reported to your logger / user interface). It never ends the foreach and exits the method before you can assign your data source.

I would suggest that your second split, one of the entries does not actually contain your delimiter ,?; , so the show1 array is 1 in length and does not contain a "name" entry. When you try to access show1[1] , it throws an IndexOutOfRangeException .

Aside, can I suggest you investigate the use of simpler delimiters or, even better, use some form of XML serialization (or JSON or another) to read your data.

EDIT: I see from your published code in your comments that the problem is the last entry. Given hlj,?;lljhjh:?;hhmm,?;drr:?;oo,?;hello:?;ff,?;ff:?; , your first String.Split operation on :?; will result in an empty string as the last record. Thus, when you try to perform the second division on ,?; , it splits into empty ones and returns an array with a single String.Empty entry. When you press show1[1] , an exception will be thrown.

If you changed your first split to use StringSplitOptions.RemoveEmptyEntries , it should eliminate the empty entry:

 string[] shows = text.Split(new[] { ":?;" }, StringSplitOptions.RemoveEmptyEntries); 

If you like, you can add a check, for example if (show1.Length == 2) , then you can avoid bad data (but you might prefer to report it so you can fix it). If your program writes these bad data yourself, you may need to do some quick unit tests to make sure you always write / read reliable data.

+9
source

All Articles