user274364
user274364

Reputation: 1857

Linq to Object -Object update

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?

Upvotes: 2

Views: 7750

Answers (4)

James Curran
James Curran

Reputation: 103575

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.

Upvotes: 0

Adam Robinson
Adam Robinson

Reputation: 185703

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.

Upvotes: 4

kwcto
kwcto

Reputation: 3504

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.

Upvotes: 4

SLaks
SLaks

Reputation: 888185

No; you need to use a foreach loop.

Upvotes: 4

Related Questions