Reputation: 49
How to update multiple property of object in list?
foreach(emp e in emps){
list1.Where(x => x.ID == e.ID && x.Salary < 5000).FirstOrDefault().Level = B;
list1.Where(x => x.ID == e.ID && x.Salary < 5000).FirstOrDefault().Hike = e.Hike;
list1.Where(x => x.ID == e.ID && x.Salary < 5000).FirstOrDefault().Salary = (e.Hike + 100)*e.Salary/100 ;
}
I dont want to use multiple in-line query for each field. Also it should update same single object. Note : e.ID is not unique key. list1 can contain duplicate Ids
Upvotes: 3
Views: 2348
Reputation: 45
I wanted a solution that updates the object in place, which I suspect the OP wants too.
int i = yourList.FindIndex(x => x.ID == "123" && x.Salary < 5000);
if (i > 0) {
yourList[i].Level = "foo";
yourList[i].Hike = "bar";
}
Upvotes: 0
Reputation: 49
After giving lots of try. Looks like these will work :
foreach(emp e in emps){
int index = list1.FindIndex(x => x.ID == e.ID && x.Salary < 5000);
if(index != -1)
{
list1[index].Level = 'B';
list1[index].Hike = e.Hike;
list1[index].Salary = (e.Hike + 100)*e.Salary/100;
}
}
What you guys feel ?
Upvotes: 1
Reputation: 2654
No explicit search, no nested loops: (if ID is your primary Key)
foreach(item in list.Join(emps, x=>x.ID, e=>e.empID, (l,e)=> (l,e)).Where(x => x.l.Salary > 5000))
{
item.l.Level = B;
item.l.Hike = item.e.Hike;
item.l.Salary = (item.e.Hike + 100) * item.e.Salary / 100;
}
Append .OfType() if you need to.
Upvotes: -1
Reputation: 3576
Replace Foo
with your class
foreach (emp e in emps)
{
if (list.FirstOrDefault(x => x.ID == e.empID && x.Salary > 5000) is Foo f)
{
f.Level = B;
f.Hike = e.Hike;
f.Salary = (e.Hike + 100) * e.Salary / 100;
}
}
Upvotes: 0
Reputation: 45947
You need to query your list only once
foreach (emp e in emps)
{
var item = list.FirstOrDefault(x => x.ID == e.empID && x.Salary > 5000);
if (item != null)
{
item.Level = B;
item.Hike = e.Hike;
item.Salary = (e.Hike + 100) * e.Salary / 100;
}
}
Upvotes: 8