Finding distinct employee names count using Lambda expression in C#

In this program, we are going to read distinct employ names count using lambda expression

Error Message:

Error      CS1061  'List<Employee>' does not contain a definition for 'Select' and no accessible extension method 'Select' accepting a first argument of type 'List<Employee>' could be found (are you missing a using directive or an assembly reference?)
Error      CS0122  'Employee.Eid' is inaccessible due to its protection level ConsoleApp1                C:\Users\ranga\source\repos\ConsoleApp1\ConsoleApp1\Program.cs

Error Description:
We need to add System.Linq namespace to overcome error CS1061.
In this program Employee object Eid is not public so we are facing this error - CS0122

using System;
using System.Collections.Generic;


namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
             var employees = new List<Employee> {
                new Employee { Name = "Surya", EId = 1, Salary= 4000 },
                new Employee { Name = "Infoware", EId = 2, Salary = 12.50M },
                new Employee { Name = "Surya", EId = 3, Salary = 1.15M },
                new Employee { Name = "Infoware", EId = 4, Salary = 2.00M },
                new Employee { Name = "Surya Infoware", EId = 5, Salary = 1000.0M }
              };

            var DistinctEmployNames = employees.Select(p => p.Name).Distinct().Count();
            Console.WriteLine("Distinct employee names {0} ", DistinctEmployNames.ToString());
        }
    }
    class Employee
    {
         public string Name;
         int EId;
         public decimal Salary;
    }
}

Error Solution:
We need to add System.Linq namespace to overcome error CS1061.
We need to add public to Eid to overcome error CS0122.
using System;
using System.Collections.Generic;
using System.Linq;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
             var employees = new List<Employee> {
                new Employee { Name = "Surya", EId = 1, Salary= 4000 },
                new Employee { Name = "Infoware", EId = 2, Salary = 12.50M },
                new Employee { Name = "Surya", EId = 3, Salary = 1.15M },
                new Employee { Name = "Infoware", EId = 4, Salary = 2.00M },
                new Employee { Name = "Surya Infoware", EId = 5, Salary = 1000.0M }
              };

            var DistinctEmployNames = employees.Select(p => p.Name).Distinct().Count();
            Console.WriteLine("Distinct employee names {0} ", DistinctEmployNames.ToString());
        }
    }
    class Employee
    {
         public string Name;
         public int EId;
         public decimal Salary;
    }
}



Output:
Share this post :

Post a comment

Please share your valuable feedback and share this article in social media.

 
Support : Ranga Rajesh Kumar
Copyright © 2019. Error Solution - All Rights Reserved
Site Designed by Ranga Rajesh Kumar