dotnet-practitioner
dotnet-practitioner

Reputation: 14148

linq query to parse my class

I need to parse my class for some purpose to come up with specific text string for each property.

 namespace MyNameSpace
    {
        [MyAttribute]
        public class MyClass
        {

            [MyPropertyAttribute(DefaultValue = "Default Value 1")]
            public static string MyProperty1
            {
                get { return "hello1"; }
            }

            [MyPropertyAttribute(DefaultValue = "Default Value 2")]
            public static string MyProperty2
            {
                get { return "hello2"; }
            }

        }
    }

Here is my linq query to parse the file where this class lives

var lines =
    from line in File.ReadAllLines(@"c:\someFile.txt")
        where line.Contains("public static string ")
    select line.Split(' ').Last();


    foreach (var line in lines)
    {
         Console.WriteLine(string.Format("\"{0}\", ", line));
    }

I am trying to output the following but I don't know how to write the linq query for this.

{"MyProperty1", "Default Value 1"}
{"MyProperty2", "Default Value 2"}

Upvotes: 1

Views: 104

Answers (2)

Tim Destan
Tim Destan

Reputation: 2028

How about this?

foreach (var propertyInfo in typeof (MyClass).GetProperties()) {
    var myPropertyAttribute =
        propertyInfo.GetCustomAttributes(false).Where(attr => attr is MyPropertyAttribute).SingleOrDefault<MyPropertyAttribute>();
    if (myPropertyAttribute != null) {
        Console.WriteLine("{{\"{0}\",\"{1}\"}}", propertyInfo.Name, myPropertyAttribute.DefaultValue);
    }
}

Upvotes: 1

mellamokb
mellamokb

Reputation: 56779

Regular expressions may be a simpler solution:

var str = File.ReadAllLines(@"c:\someFile.txt");
var regex =
    @"\[MyPropertyAttribute\(DefaultValue = ""([^""]+)""\)\]" +
    @"\s+public static string ([a-zA-Z0-9]+)";

var matches = Regex.Matches(str, regex);

foreach (var match in matches.Cast<Match>()) {
    Console.WriteLine(string.Format("{{\"{0}\", \"{1}\"}}", 
        match.Groups[2].Value, match.Groups[1].Value));
}

Sample output:

{"MyProperty1", "Default Value 1"}
{"MyProperty2", "Default Value 2"}

Demo: http://ideone.com/D1AUBK

Upvotes: 0

Related Questions