All I have is a file and a string to be searched inside it
Key
Value1
Value2
Value3
Key1
Value1
This is the structure of the file. Now, I search for a key and then read all values under it
until I find a newline (or simply a empty line)
I use this algorithm.
var valuelist = new List<string>();
using(var reader = new StreamReader(@"c:\test.txt"))
{
String a;
while( (a=reader.ReadLine())!=null)
{
if(!a.Equals("Key")) continue;
while( a == reader.ReadLine() != null) //check whether end of file is not reached.
{
if(a.Length == 0) break; //a empty line is reached.hence comeout.
valuelist.add(a);
}
}
}
-
I am using “using” because it automatically disposes the “reader” object ? Is my approach right in this case ?
-
How Can I use a LINQ expression here in this context ?
I tried the following code
var all_lines = File.ReadAllLines(@"C:\test.txt");
//How to retrieve "Values" for a given key using LINQ ?
usingin this context is very appropriateSkipWhilelooking for the key by name, followed byTakeWhilelooking for a blank line.