Q:

Loop through LINQ field values

I have a text file with placeholders such as:
Thank you for your order [OrderNo].  Your order will be shipped to:
[Name]
[Street1]
[Street2] etc
The placeholders are the field names in the database surrounded by brackets.
I want to retrieve a single record from the database like:
var order = (from o in testContext.OrderTables where o.OrderID == id select o).Single();
Then I'd like to be able to loop through the order object and get the field name, and it's value to fill in the placeholder.
Is this possible?

A:

How about this:

void Main()
{
   var text = "Thank you for your order [OrderNo]. Your order will be shipped to: [Name] [Street1] [Street2]";

   var order = new Order() {OrderNo = 1, Name="NameA", Street1 = "Address1A", Street2="Addres2A"};

   var splitted = text.Split(']').ToList();

   var orderType = (new Order()).GetType();

   var newText = text;
   splitted.ForEach(p => 
    { 
       string field = p.Substring(p.IndexOf('[') + 1);
       if (!string.IsNullOrEmpty(field))
       {
           var result = orderType.GetProperty(field).GetValue(order, null);
           //var method = orderType.GetMethod("get_"+field);
           //var result = method.Invoke(o, null);
           newText = newText.Replace("[" + field + "]", result.ToString());
       }
    });
   Console.WriteLine(newText);
}

public class Order
{
    public Order()
    {}

    public int OrderNo {get; set;}
    public string Name {get; set;}
    public string Street1 {get; set;}
    public string Street2 {get; set;}
}

I'm not sure if I like it, but it does work. :-)

