CSharp - Add member names to dynamically generated anonymous class in Select operator


We can use the object initialization features of C# to specify the anonymous class member names.


using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;

class Program/*from   www . j a  v  a  2  s . com*/
    static void Main(string[] args)
        string[] names = {
          "Python", "Java", "Javascript", "Bash", "C++", "Oracle"};
        var nameObjs = names.Select(p => new { LastName = p, Length = p.Length });
        foreach (var item in nameObjs)
           Console.WriteLine("{0} is {1} characters long.", item.LastName, item.Length);


We specified a name for each member in the lambda expression and then accessed each member by name in the Console.WriteLine method call.

Related Topic