Skip to content

Instantly share code, notes, and snippets.

@joeriks
Last active August 29, 2015 14:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joeriks/af2d2b215d684bfaa7ba to your computer and use it in GitHub Desktop.
Save joeriks/af2d2b215d684bfaa7ba to your computer and use it in GitHub Desktop.
Map multiline string to array of anonymous objects using linq
var structure = @"
Alias Document name Parent
---------------------------------
root Root DocType -1
textType Text DocType 0
";
var mapped = Regex.Split(structure, @"\r\n", RegexOptions.IgnorePatternWhitespace) /* split string into lines */
.Skip(3) /* skip headers */
.Select(line => Regex.Split(line, @"\s{2,}", RegexOptions.IgnorePatternWhitespace)) /* split by more than one space */
.Where(cols=>cols.Length==3) /* only care about lines with lines with 3 cols */
.Select(cols =>
new { /* create anonymous objects */
alias = cols[0],
name = cols[1],
parentId = Int32.Parse( cols[2] )
});
var objs2 = new []{
new []{ "root", "Root DocType", "-1"},
new []{ "textType", "Text DocType", "0"}}
.Select (t => new {
alias=(string)t[0],
name=(string)t[1],
parent=Int32.Parse(t[2])});
objs2.Dump();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment