LINQ iterate through results -
i trying read following text file:
author { name xyz blog www.test.com rating 123 } author { name xyz blog www.test.com rating 123 } author { name xyz blog www.test.com rating 123 } author { name xyz blog www.test.com rating 123 }
i using following snippet fetch author record:
public static ienumerable<string> getauthors(string path, string startfrom, string endto) { return file.readlines(path) .skipwhile(line => line != startfrom) .takewhile(line => line != endto); } public static void dosomethingwithauthors(string filename) { var result = getauthors(filename, "author", "}").tolist(); }
the above returns me 1 author details. kindly show me how fetch authors in 1 go popluate object. thank much!!
i suggest that, if file structure predicatable might use regex author details. objects want initialize not complex, can match author
bit , take values regex match groups.
the regex match authors this:
author\s*{\s*name\s+(.*?)\s+blog\s+(.*?)\s+rating\s+(.*?)\s*}
your values in group 1,2 , 3.
edit:
if doesn't make difference you, can use readtoend() method , can parse whole file content string:
http://msdn.microsoft.com/en-us/library/system.io.streamreader.readtoend(v=vs.100).aspx
as regex solution - check out:
http://msdn.microsoft.com/en-us/library/twcw2f1c.aspx
an adapted version - might need tweaking in general should work:
string text = [yourinputfileasstring] string pat = @"author\s*{\s*name\s+(.*?)\s+blog\s+(.*?)\s+rating\s+(.*?)\s*}"; regex r = new regex(pat, regexoptions.ignorecase | regexoptions.singleline); match m = r.match(text); var authors = new list<author>(); while (m.success) { var name = m.groups[1].value; var blog = m.groups[2].value; var rating = m.groups[3].value; var author = new author(name, blog, rating); authors.add(author); m = m.nextmatch(); }
Comments
Post a Comment