Friday 15 May 2015

c# - Linq with Regex -



c# - Linq with Regex -

i have matches of regex pattern , i'm having difficulties designing linq around produce desired output.

the info fixed lengths: 1231234512341234567

lengths in case are: 3, 5, 4, 7

the regex pattern used is: (.{3})(.{5})(.{4})(.{7})

this works fine , matched results of pattern expected, however, desired output proving difficult. in fact, i'm not called in sql terms - except maybe pivot query. desired output take values each of groups @ given position , concatenate them example:

field1:value1;value2;value3;valuen;field2:value2;value3;valuen;

using below linq expression, able field1-value1, field2-value2, etc...

var matches = regex.matches(data, re).cast<match>(); var xmlresults = m in matches e in elements select string.format("<{0}>{1}</{0}>", e.name, m.groups[e.ordinal].value);

but can't seem figure out how values @ position 1 "groups" using element's ordinal, values @ position 2 , on.

the "elements" in illustration collection of field names , ordinal positions (starting @ 1). so, this:

public class element { public string name { get; set; } public int ordinal { get; set; } } var elements = new list<element>{ new element { name="field1", ordinal=1 }, new element { name="field2", ordinal=2 } };

i've reviewed bunch of various linq expressions , dug pivot type linq expressions, none of them me close - utilize bring together operator don't think possible.

does have thought how create linq?

you should able changing query select elements only, , bring in matches through string.join, this:

// utilize tolist avoid iterating matches multiple times var matches = regex.matches(data, re).cast<match>().tolist(); // each element, bring together matches, , pull in value e.ordinal var xmlresults = elements.select(e => string.format( "<{0}>{1}</{0}>" , e.name , string.join(";", matches.select(m => m.groups[e.ordinal].value)) );

note: not best way of formatting xml. improve off using 1 of .net's libraries making xml, such linq2xml.

c# linq

No comments:

Post a Comment