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

  • SEARCH
  • Home
  • 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 8258431
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 8, 20262026-06-08T02:32:03+00:00 2026-06-08T02:32:03+00:00

I’ve bending my mind for a while, but I think I’m missing something, so

  • 0

I’ve bending my mind for a while, but I think I’m missing something, so may be someone will help.

Let’s say I have following mapper class:

public class Mapping<TSource, TResult>
{
    private readonly Action<TSource, TResult> setter;

    public Mapping(Expression<Func<TSource, TResult>> expression)
    {
        var newValue = Expression.Parameter(expression.Body.Type);
        var body = Expression.Assign(expression.Body, newValue);
        var assign = Expression.Lambda<Action<TSource, TResult>>(body, expression.Parameters[0], newValue);

        setter = assign.Compile();
    }

    public void Assign(TSource instance, TResult value)
    {
        setter(instance, value);
    }
}

And it is working fine:

    [Test]
    public void ShouldMapProperty()
    {
        var testClass = new TestClass();

        var nameMapping = new Mapping<TestClass, string>(x => x.Name);
        var ageMapping = new Mapping<TestClass, int>(x => x.Age);

        nameMapping.Assign(testClass, "name");
        ageMapping.Assign(testClass, 10);

        Assert.AreEqual("name", testClass.Name);
        Assert.AreEqual(10, testClass.Age);       
    }

Thing is, that I would like to keep mappings for single object type into some collection and TResult is getting in the way, as long as different properties have different types.
How to get rid of TResult nicely?

Update:
looks like I wasn’t clear enough, so this would be sample how would I use it:

 public class Mapping<TSource, TResult>
{
    private readonly Action<TSource, TResult> setter;
    private readonly string columnName;

    public Mapping(Expression<Func<TSource, TResult>> expression, string columnName)
    {
        this.columnName = columnName;            

        var newValue = Expression.Parameter(expression.Body.Type);
        var body = Expression.Assign(expression.Body, newValue);
        var assign = Expression.Lambda<Action<TSource, TResult>>(body, expression.Parameters[0], newValue);

        setter = assign.Compile();
    }

    public void Assign(TSource instance, DataRow row)
    {
        setter(instance, row[columnName]);
    }
}

And then I would have some MappingConfiguration class, that would let me do this:

MappingConfiguration.For<TestClass>()
  .Map(x => x.Name, "FirstName")
  .Map(x => x.Age, "Age");

And finaly some MappingEngine class, that would take DataTable and MappingConfiguration as input and produce IEnumerable<TestClass> as output.

Update 2:
I’ve modified initial version to this:

public class Mapping2<TSource>
{
    private readonly Delegate setter;

    public Mapping2(Expression<Func<TSource, object>> expression)
    {
        var newValue = Expression.Parameter(expression.Body.Type);
        var body = Expression.Assign(expression.Body, newValue);
        var assign = Expression.Lambda(body, expression.Parameters[0], newValue);            

        setter = assign.Compile();
    }

    public void Assign(TSource instance, object value)
    {
        setter.DynamicInvoke(instance, value);
    }
}

And it almost works.
By almost I mean it works with reference type properties, and with value type properties I get:

System.ArgumentException : Expression must be writeable
Parameter name: left

  • 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-06-08T02:32:04+00:00Added an answer on June 8, 2026 at 2:32 am

    I’ve managed to do it, source code below. It runs somewhat faster than Automapper (not sure if my Automapper configuration is the fastest for this task), benchmark is not bulletproof, but on my machine to map 5 million rows took 20.16 seconds using my written mapper and 39.90 using Automapper, although it seems that Automapper uses less memory for this task (haven’t measured it, but with 10 million rows Automapper gives result and my mapper fails with OutOfMemory).

    public class MappingParameter<TSource>
    {
        private readonly Delegate setter;
    
        private MappingParameter(Delegate compiledSetter)
        {
            setter = compiledSetter;
        }
    
        public static MappingParameter<TSource> Create<TResult>(Expression<Func<TSource, TResult>> expression)
        {
            var newValue = Expression.Parameter(expression.Body.Type);
            var body = Expression.Assign(expression.Body, newValue);
            var assign = Expression.Lambda(body, expression.Parameters[0], newValue);
    
            var compiledSetter = assign.Compile();
    
            return new MappingParameter<TSource>(compiledSetter);
        }
    
        public void Assign(TSource instance, object value)
        {
            object convertedValue;
            if (!setter.Method.ReturnType.IsAssignableFrom(typeof(string)))
            {
                convertedValue = Convert.ChangeType(value, setter.Method.ReturnType);
            }
            else
            {
                convertedValue = value;
            }
    
            setter.DynamicInvoke(instance, convertedValue);
        }
    }
    
    public class DataRowMappingConfiguration<TSource>
    {
        private readonly Dictionary<string, MappingParameter<TSource>> mappings =
            new Dictionary<string, MappingParameter<TSource>>();
    
        public DataRowMappingConfiguration<TSource> Add<TResult>(string columnName,
                                                                 Expression<Func<TSource, TResult>> expression)
        {
            mappings.Add(columnName, MappingParameter<TSource>.Create(expression));
            return this;
        }
    
        public Dictionary<string, MappingParameter<TSource>> Mappings
        {
            get
            {
                return mappings;
            }
        }
    }
    
    public class DataRowMapper<TSource>
    {
        private readonly DataRowMappingConfiguration<TSource> configuration;
    
        public DataRowMapper(DataRowMappingConfiguration<TSource> configuration)
        {
            this.configuration = configuration;
        }
    
        public IEnumerable<TSource> Map(DataTable table)
        {
            var list = new List<TSource>(table.Rows.Count);
    
            foreach (DataRow dataRow in table.Rows)
            {
                var obj = (TSource)Activator.CreateInstance(typeof(TSource));
    
                foreach (var mapping in configuration.Mappings)
                {
                    mapping.Value.Assign(obj, dataRow[mapping.Key]);
                }
    
                list.Add(obj);
            }
    
            return list;
        }
    }
    
    public class TestClass
    {
        public string Name { get; set; }
        public int Age { get; set; }
    }
    
    [TestFixture]
    public class DataRowMappingTests
    {      
        [Test]
        public void ShouldMapPropertiesUsingOwnMapper()
        {            
            var mappingConfiguration = new DataRowMappingConfiguration<TestClass>()
                .Add("firstName", x => x.Name)
                .Add("age", x => x.Age);
    
            var mapper = new DataRowMapper<TestClass>(mappingConfiguration);                      
    
            var dataTable = new DataTable();
            dataTable.Columns.Add("firstName");
            dataTable.Columns.Add("age");
    
            for (int i = 0; i < 5000000; i++)
            {
                var row = dataTable.NewRow();
                row["firstName"] = "John";
                row["age"] = 15;
    
                dataTable.Rows.Add(row);                
            }
    
            var start = DateTime.Now;
    
            var result = mapper.Map(dataTable).ToList();
    
            Console.WriteLine((DateTime.Now - start).TotalSeconds);
    
            Assert.AreEqual("John", result.First().Name);
            Assert.AreEqual(15, result.First().Age);
        }
    
        [Test]
        public void ShouldMapPropertyUsingAutoMapper()
        {
            Mapper.CreateMap<DataRow, TestClass>()
                .ForMember(x => x.Name, x => x.MapFrom(y => y["firstName"]))
                .ForMember(x => x.Age, x => x.MapFrom(y => y["age"]));
    
            var dataTable = new DataTable();
            dataTable.Columns.Add("firstName");
            dataTable.Columns.Add("age");
    
            for (int i = 0; i < 5000000; i++)
            {
                var row = dataTable.NewRow();
                row["firstName"] = "John";
                row["age"] = 15;
    
                dataTable.Rows.Add(row);
            }
    
            var start = DateTime.Now;
    
            var result = dataTable.Rows.OfType<DataRow>().Select(Mapper.Map<DataRow, TestClass>).ToList();         
    
            Console.WriteLine((DateTime.Now - start).TotalSeconds);
    
            Assert.AreEqual("John", result.First().Name);
            Assert.AreEqual(15, result.First().Age);
        }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
I have a French site that I want to parse, but am running into
I have a .ini file as follows: [playlist] numberofentries=2 File1=http://87.230.82.17:80 Title1=(#1 - 365/1400) Example
link Im having trouble converting the html entites into html characters, (&# 8217;) i
I have just tried to save a simple *.rtf file with some websites and
I want to count how many characters a certain string has in PHP, but
I have a jquery bug and I've been looking for hours now, I can't
this is what i have right now Drawing an RSS feed into the php,
I have this code to decode numeric html entities to the UTF8 equivalent character.
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this

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.