0

I´ve got a textfile, where every line is separated with \n an every value in a row is separated by \t.

StreamReader sr = new StreamReader(dlg.FileName);
String ganzes = sr.ReadToEnd();
String[] allezeilen = ganzes.Split('\n');
string[] ssa = allezeilen[i].Split('\t');
foreach (string h in ssa)
{
   String verwendungszw = h.Contains("Verwendungszweck");
}

Now, in the foreach loop, I try to find the entry in ssa that contains "Verwendungszweck". Ok, that is easy. But I don´t need the entry with "Verwendungszweck" in it, I need the next one.

How can I get the next entry?

user896692
  • 2,351
  • 7
  • 36
  • 57

4 Answers4

5

One option would be to use LINQ:

string value = ssa.SkipWhile(x => !x.Contains("Verwendungszweck"))
                  .ElementAtOrDefault(1);

That's probably the simplest way to do it if that's all you need. value will be null if no elements of ssa contained Verwendungszweck, or if only the last element did.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
1

Change loop to

for (int i = 0; i < ssa.Length; i++) { 
    if (ssa[i].Contains("Verwendungszweck")) {
        String verwendungszw = ssa[i+1];
    }
}
Krzysztof
  • 15,900
  • 2
  • 46
  • 76
  • wow, what a shame for me. Thanks, I will mark your post as solution in a few minutes. – user896692 Jan 03 '12 at 16:45
  • Use `i < ssa.Length - 1` if you want to avoid throwing an exception when the last entry contains "Verwendungszweck". – Brian Jan 04 '12 at 14:36
1

Answer without bounds checking and verification that the search string is in the array:

int pos = Array.IndexOf(ssa, "Verwendungszweck");
string value = ssa[pos + 1];
D Stanley
  • 149,601
  • 11
  • 178
  • 240
0

Note that you don't define what is 'i'

StreamReader sr = new StreamReader(dlg.FileName);
String ganzes = sr.ReadToEnd();
String[] allezeilen = ganzes.Split('\n');
foreach (string CurrentLine in allezeilen)
  {
     string[] ssa = CurrentLine.Split('\t');
     for (CurrentRowIndex=0, CurrentRowIndex<ssa.Count, CurrentRowIndex++)
         {
           if ssa[CurrentRowIndex].Contains("Verwendungszweck")
                   verwendungszw =ssa[++CurrentRowIndex] ; // or add it to a list and maybe exit for 
         }
  }
GameAlchemist
  • 18,995
  • 7
  • 36
  • 59