In LINQ to Object
context ,can i update an object in memory.
I mean i can create new type like
var query =from e in empList
select new {id=e.id,salary=e.salary * (10/100) };
can i update an object?
In LINQ to Object
context ,can i update an object in memory.
I mean i can create new type like
var query =from e in empList
select new {id=e.id,salary=e.salary * (10/100) };
can i update an object?
Anonymous types are immutable. If the type is not anonymous, you can dump the collection to a List and modify that:
(from e in empList)
.ToList()
.ForEach(e => {
e.salary = 999;
})
;
Notice I'm using block syntax in the lambda.
That depends on what you're asking.
If you're asking: Can I use a LINQ statement to update data on the elements of a collection? Then the answer is simply no; LINQ is a query language, not a data modification language. Just use a foreach
loop on the original collection as you would have done prior to .NET 3.5/C# 3.0. Nothing to see here.
If you're asking Can I update the values on the type I created in the query in my question?, then the answer is "sortof". The type you're creating by using new { ... }
is an anonymous type, which makes it immutable (read only). There's no clean way to do what you're after, but you could do something like:
var query = from e in empList
select new { id = e.id, salary = e.salary / 10.0, record = e }
Doing this will give you a reference to the original object via the record
property, which you can change values on. Realize, though, that the values on your anonymous type (id
and salary
, in this case) will not reflect any changes made to the referenced object in record
.
foreach(var element in empList)
{
element.record.salary = 100.0;
}
This will update the salary property on the original item, but element.salary
will still reflect the original value that was calculated in the query, not the new salary value / 10.0
.
Sure, that will work just fine.
Note, however, that the object you are create, while looking like and having the same properties as an Emp, will be a distinct object type.
To elaborate, if you were to say:
var query =from e in empList
select e;
You are creating a collection of Emp objects. When you say:
var query =from e in empList
select new {id=e.id,salary=e.salary * (10/100) };
You are creating a collection of anonomous objects which have the same form as Emp objects. You can assign values which may be different from the original empList value, while you are creating it, but once that statement is complete, thosee values cannot be changed again. And nothing here will affect the values in empList.