Reputation: 331
I am creating a Generic List of objects of Employee class.
List<Employee> EmployeeList = new List<Employee>
{
new Employee { ecode=1, ename="Rohit", salary=20000, mgrid="3" },
new Employee { ecode=2, ename="Sangeeta", salary=12000, mgrid="5"},
new Employee { ecode=3, ename="Sanjay", salary=10000, mgrid="5"},
new Employee { ecode=4, ename="Arun", salary=25000, mgrid="3"},
new Employee { ecode=5, ename="Zaheer", salary=30000, mgrid=null}
};
'mgrid' is the Employee ID of the Manager. I want just increment the salary of the Managers. I tried doing it using the following approach, but salaries of all the employees are getting incremented.
var mgrsal = from e1 in emplst
join e2 in emplst
on e1.ecode.ToString() equals e2.mgrid into empdata
select new Employee
{
ecode = e1.ecode,
ename=e1.ename,
salary=e1.salary*1.1,
mgrid = e1.mgrid
};
I am coding in C#.net in Visual Studio IDE and I also tried to use Contains() and Any() methods, but I am unable to use.
Upvotes: 0
Views: 478
Reputation: 125620
LINQ is all about querying, not updating. You can use LINQ to get all managers from the list,
var managers = from e in emplst
where emplst.Any(x => x.mgrid == e.ecode.ToString())
select e;
or using JOIN
(it would require implementing Equals
and GetHashCode
methods on Employee
class to make Distinct
work:
var managers = (from e in emplst
join e2 in emplst on e.ecode.ToString() equals e2.mgrid
select e).Distinct();
and then iterate over and change the salary:
foreach(var manager in managers)
manager.salary *= 1.1;
Upvotes: 1