Note that there are some explanatory texts on larger screens.

plurals
  1. POUsing C# LINQ Expressions for both Value Types and Reference Types
    primarykey
    data
    text
    <p>I'm using MVC for REST so that I can take advantage of Razor for outputting different types. CSV is one of those outputs. Instead of writing this template for each input type:</p> <pre><code>ID,Created,Content @foreach (var item in Model.TimeData) { &lt;text&gt;@item.ID,@item.Created,"@Html.Raw(item.Content.Replace("\"", "\"\""))"&lt;/text&gt; } </code></pre> <p>I wanted to make use of <code>params</code> and <code>System.Linq.Expressions.Expression</code> to write something like this:</p> <pre><code>@{ Html.WriteCsv&lt;TimeObject&gt;(Model.TimeData, p =&gt; p.ID, p =&gt; p.Created, p =&gt; p.Content); } </code></pre> <p>I started writing a generic <code>HtmlHelper</code> and quickly realized I had problems with value types (memberExpression will be null). The code below attempts to just write out the CSV heading (ID,Created,Content), but it only outputs "Content" (because ID and Created are value types (<code>int</code> and <code>DateTime</code>).</p> <pre><code>public static void WriteCsv&lt;TModel&gt;(this HtmlHelper htmlHelper, List&lt;TModel&gt; list, params Expression&lt;Func&lt;TModel, object&gt;&gt;[] expressions) { foreach (var expression in expressions) { MemberExpression memberExpression = expression.Body as MemberExpression; if (memberExpression != null) { var propertyInfo = (PropertyInfo)memberExpression.Member; htmlHelper.ViewContext.Writer.Write(propertyInfo.Name + Environment.NewLine); } } } </code></pre> <p>I tried replacing <code>object</code> with <code>dynamic</code>, thinking that would work, but when I quick watch <code>expression.Body</code>, it still seems to think it's dealing with an object (the <code>DebugView</code> property is <code>(System.Object)$p.ID</code>).</p> <p>Is this impossible in C# 4.0?</p> <p>Here's the type I'm using it on:</p> <pre><code>[DataContract(IsReference = true, Namespace = "urn:test:TimeObject")] public class TimeObject { [DataMember] public long ID { get; set; } [DataMember] public string Content { get; set; } [DataMember] public DateTime Created { get; set; } } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload