You must Sign In to post a response.
  • Category: LINQ

    What is the use of new keyword in linq

    Hi All,
    One doubt . Why we using select new {name} in linq query
    pls give some example that where to use select new {name}


    Thanks and Regards,
    A.L.Chellappan
  • #754744
    This will create the New object based on the condition.


    SO the NEW is to create a new object of that class type.

    Thanks & Regards
    Anil Kumar Pandey
    Microsoft MVP, DNS MVM

  • #754747
    Hi,
    its actually create a new object or new name where we assign the actual field of a member class.
    Here one examples:
    using System;
    using System.Linq;
    using System.Collections.Generic;


    public class Demo
    {
    static Employee[] employees;

    public static int Main()
    {
    employees = new Employee[]
    {
    new Employee(51478565, "chitaranjan", "mallick", 24.68M),
    new Employee(51467896, "xyz", "sahoo", 204.15M),
    new Employee(279374, "Ranjan", "PR", 15.55M)
    };

    var LNQMembers = from empls
    in employees
    select new
    {
    Number = empls.EmployeeNumber,
    FName = empls.FirstName,
    LName = empls.LastName,
    Wage = empls.HourlySalary
    };

    Console.WriteLine("+========+============+===========+========+");
    Console.WriteLine("| Empl # | First Name | Last Name | Salary |");
    foreach (var members in LNQMembers )
    {
    Console.WriteLine("+--------+------------+-----------+--------+");
    Console.WriteLine("| {0,6} | {1,-10} | {2,-9} | {3,6} |", members .Number,
    members .FName, members .LName, members .Wage);
    }


    Console.WriteLine("+=======+============+===========+=========+");

    Console.WriteLine();
    return 0;
    }
    }

    Hope u understand the concept of new kyword in Linq

    Thanks,
    chitaranjan

  • #754770
    You can use select new to return new anonymously typed objects , to return new anonymously typed objects while select without new, with no transformation
    Example

    using System;
    using System.Linq;

    class Program
    {
    static void Main()
    {
    string[] array = { "Mango", "tiger", "three", "fox", "", "swan" };

    var result = from element in array
    select new { Value = element, Id = Id(element) };

    foreach (var anonymous in result)
    {
    string value = anonymous.Value;
    int id = anonymous.Id;

    Console.WriteLine(anonymous);
    }
    }

    static int _value;
    static int Id(string element)
    {
    return string.IsNullOrEmpty(element) ?
    -1 :
    _value++;
    }
    }

  • #754776
    Hi,

    for ur clear understanding, again i ll add the Runable code.. please follow it in console application.

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

    namespace Console_Demo
    {
    public class Employee
    {
    public int EmployeeNumber;
    public string FirstName;
    public string LastName;
    public decimal HourlySalary;

    public Employee(int number,
    string firstName ,
    string lastName,
    decimal salary)
    {
    EmployeeNumber = number;
    FirstName = firstName;
    LastName = lastName;
    HourlySalary = salary;
    }
    }


    class Program
    {


    public class Demo
    {
    static Employee[] employees;

    public static int Main()
    {
    employees = new Employee[]
    {
    new Employee(51478565, "chitaranjan", "mallick", 24.68M),
    new Employee(51467896, "xyz", "sahoo", 204.15M),
    new Employee(279374, "Ranjan", "PR", 15.55M)
    };

    var LNQMembers = from empls
    in employees
    select new
    {
    Number = empls.EmployeeNumber,
    FName = empls.FirstName,
    LName = empls.LastName,
    Wage = empls.HourlySalary
    };

    Console.WriteLine("+========+============+===========+========+");
    Console.WriteLine("| Empl # | First Name | Last Name | Salary |");
    foreach (var members in LNQMembers )
    {
    Console.WriteLine("+--------+------------+-----------+--------+");
    Console.WriteLine("| {0,6} | {1,-10} | {2,-9} | {3,6} |", members .Number,
    members .FName, members .LName, members .Wage);
    }


    Console.WriteLine("+=======+============+===========+=========+");

    Console.WriteLine();
    return 0;
    }
    }
    static void Main(string[] args)
    {
    }
    }
    }
    hope u are understood..

    Thnaks,
    chitaranjan

  • #755146
    "new" keyword in Linq query is used to create anonymous objects in the resultant collection.

    ** Anonymous object can have a different set of properties based on source data.

    // Sample.................................................................
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;

    namespace ConsoleApplication1
    {
        class Program
        {
            static void Main(string[] args)
            {
                // Entity Collection
                List<Project> projects = new List<Project>();
                projects.Add(new Project { Id = 1, Name = "Account", DaysCompleted = 45,  Type = "Desktop" });
                projects.Add(new Project { Id = 2, Name = "Payroll", DaysCompleted = 95,  Type = "Web" });
                projects.Add(new Project { Id = 3, Name = "Orders",  DaysCompleted = 145, Type = "Web" });
                projects.Add(new Project { Id = 4, Name = "Library", DaysCompleted = 425, Type = "Desktop" });
                projects.Add(new Project { Id = 5, Name = "SMS",     DaysCompleted = 58,  Type = "Service" });
                projects.Add(new Project { Id = 6, Name = "Shopping",DaysCompleted = 112, Type = "Web" });

                // Query
                var formattedList = from p in projects
                                    where p.Type.Equals("Web")
                                    select new { projectStatus = String.Format("{0} days completed for project ({1}: {2})", p.DaysCompleted, p.Id, p.Name) };

                // Formatted Result
                Console.WriteLine("Web projects status ...\n");
                foreach (var v in formattedList)
                {
                    Console.WriteLine(v.projectStatus);
                }
                Console.ReadKey();
            }
        }

        
        // Entity class
        public class Project
        {
            public int Id { get; set; }
            public string Name { get; set; }
            public string Type { get; set; }
            public int DaysCompleted { get; set; }
        }
    }

    //Output....................................................................
    Web projects status ...
    95 days completed for project (2: Payroll)
    145 days completed for project (3: Orders)
    112 days completed for project (6: Shopping)




    Hope this helps.
    Thanks


  • Sign In to post your comments