Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6162011
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 23, 20262026-05-23T21:34:47+00:00 2026-05-23T21:34:47+00:00

I have refactored out a generic CSV builder for List using lambda expressions to

  • 0

I have refactored out a generic CSV builder for List using lambda expressions to access the correct values

public static string ToCsv<TModel>(this List<TModel> list, string delimiter, string lineBreak, string valueWrap, params Expression<Func<TModel, object>>[] expressions)
{
  var sb = new StringBuilder();

  var headers = expressions.Select(m => String.Format("{0}{1}{0}", valueWrap, GetPropertyName(m))).ToArray();
  sb.Append(String.Format("{0}{1}", String.Join(delimiter, headers), lineBreak));

  foreach (var listItem in list)
  {
    var values = expressions.Select(m => String.Format("{0}{1}{0}", valueWrap, m.Compile()(listItem))).ToArray();
    sb.Append(String.Format("{0}{1}", String.Join(delimiter, values), lineBreak));
  }

  return sb.ToString();
}

This works well, however because I am trying to move this into some common code for several projects across several servers to access. I cannot reference the System.Web.Mvc assembly

Is there a good way to access the DisplayName Attribute and if that doesnot exist, access the variable name?

My current attempt access the ((MemberExpression) expression.Body).Member.Name however it will not work if it has to convert a value to string. (ie passing an int and implicitly converting)

A second attempt of iterating over the attributes did not work for inner class (ie model => model.innerClass.property)

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-23T21:34:49+00:00Added an answer on May 23, 2026 at 9:34 pm

    With a couple simple helper functions, you can eliminate all reference to the System.Web.Mvc assembly. You’ll also notice in the example below that (model => model.member.property) works.

    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.Linq;
    using System.Linq.Expressions;
    using System.ComponentModel;
    using System.Reflection;
    
    namespace Test
    {
        public class Program
        {
            public static void Main(string[] args)
            {
                List<Class1> foobars = new List<Class1>();
                foobars.Add(new Class1 { Foo = "Hello world!", Bar = -1, Skip = false, Ref = new Class2 { ToBe = true } });
    
                string result = foobars.ToCsv(",", Environment.NewLine, "\"", m => m.Foo, m => m.Bar, m => m.Ref.ToBe);
            }
    
            public class Class1
            {
                [DisplayName("Foo Property")]
                public string Foo { get; set; }
    
                public int Bar { get; set; }
    
                [DisplayName("Skipped Property")]
                public bool Skip { get; set; }
    
                [DisplayName("Reference")]
                public Class2 Ref { get; set; }
            }
    
            public class Class2
            {
                [DisplayName("To Be or Not To Be")]
                public bool ToBe { get; set; }
            }
        }
    
        public static class Extensions
        {
            public static string ToCsv<TModel>(this List<TModel> list, string delimiter, string lineBreak, string valueWrap, params Expression<Func<TModel, object>>[] expressions)
            {
                var sb = new StringBuilder();
    
                var headers = expressions.Select(m => String.Format("{0}{1}{0}", valueWrap, GetDisplayName(m))).ToArray();
                sb.Append(String.Format("{0}{1}", String.Join(delimiter, headers), lineBreak));
    
                foreach (var listItem in list)
                {
                    var values = expressions.Select(m => String.Format("{0}{1}{0}", valueWrap, m.Compile()(listItem))).ToArray();
                    sb.Append(String.Format("{0}{1}", String.Join(delimiter, values), lineBreak));
                }
    
                return sb.ToString();
            }
    
            // Get DisplayName, otherwise fallback to Name
            private static string GetDisplayName(LambdaExpression memberReference)
            {
                MemberInfo info = GetMemberInfo(memberReference);
                DisplayNameAttribute displayNameAttr = Attribute.GetCustomAttribute(info, typeof(DisplayNameAttribute)) as DisplayNameAttribute;
                return (displayNameAttr != null ? displayNameAttr.DisplayName : info.Name);
            }
    
            // Can be swapped for your favourite GetMemberInfo/GetPropertyInfo utility method (there are many out there)
            // Source: http://blog.baltrinic.com/software-development/dotnet/extension-methods-for-converting-lambda-expression-to-strings
            private static MemberInfo GetMemberInfo(LambdaExpression memberReference)
            {
                MemberExpression memberExpression;
                var unary = memberReference.Body as UnaryExpression;
                if (unary != null)
                    //In this case the return type of the property was not object,
                    //so .Net wrapped the expression inside of a unary Convert()
                    //expression that casts it to type object. In this case, the
                    //Operand of the Convert expression has the original expression.
                    memberExpression = unary.Operand as MemberExpression;
                else
                    //when the property is of type object the body itself is the
                    //correct expression
                    memberExpression = memberReference.Body as MemberExpression;
    
                if (memberExpression == null || !(memberExpression.Member is MemberInfo))
                    throw new ArgumentException("Expression was not of the form 'x => x.member'.");
    
                return memberExpression.Member;
            }
        }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have refactored some UIView sub-classes into a static library. However, when using Interface
I have the following code, I want to refactor the duplication out of: public
Have you refactored from an ActiveRecord to a DataMapper pattern? What conditions prompted the
I have two tables (renamed/refactored for illustrative purposes) with a Many-To-Many relationship in an
I have two methods: Public Function GetTotalLimit(ByVal entity As Entity) As Int64 Return (From
Suppose I have a function like this: public void AddEntry(Entry entry) { if (entry.Size
We have a big body of code that was refactored so that stuff which
I have a quick question that I could not figure out in the docs
I have some existing code that I've used to write out an image to
I have repetitive code that i am trying to refactor into a generic function

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.