kbvishnu
kbvishnu

Reputation: 15630

.NET - Get the reference of an object from ListOfObject

This is my employee class

public class Employee {

  public String Name  {get ;set ;}
  public int ID  {get ;set ;}

}

This is my list of employees

Public  List<Employee>  lstEmployee ;
lstEmployee=new List<Employee>();

lstEmployee.Add(new Employee() { Name ="Abc", Id=1});
lstEmployee.Add(new Employee() { Name ="Xyz", Id=2});
lstEmployee.Add(new Employee() { Name ="Pqr", Id=3});

So I can query the employee using this

Employee emp = lstEmployee. Where(emp=>emp.ID==1);

If I print emp.Name and emp.ID , I will get Abc and 1 respectively.

Now I change the values

Emp.Name="Test"

The value based on the local variable will be updated, but the value of Name in lstEmployee having ID as 1 will be unchanged.

Is there any way to get the reference of the object, so that if we change the property then it will update the list.

Please forgive me if this is a non sense.

I believe I can achieve this by directly applying this on the list , may be like lstEmployee. Where(emp=>emp.ID==1).Name="Test".

But in my current scenario, there is a function which returns the Emp object from the list and I need to update back. So I think about getting reference . Thanks in advance

Upvotes: 0

Views: 121

Answers (3)

mehmet mecek
mehmet mecek

Reputation: 2685

List already keeps references.

Employee emp = lstEmployee.First(emp=>emp.ID==1);

Here emp points the same instance with the pointer inside the list.

So what you said is wrong (the value of Name in lstEmployee having ID as 1 will be unchanged.) It will be changed.

Upvotes: 1

Mongi HAMMAMI
Mongi HAMMAMI

Reputation: 29

Where doesn't return a single object, but a collection. I don't know how you can access the Name property from Where(emp=>emp.ID==1).Name="Test".

I suggest to use FirstOrDefault instead of Where.

Employee emp = lstEmployee.FirstOrDefault(emp=>emp.ID==1);

Upvotes: 1

Joel Coehoorn
Joel Coehoorn

Reputation: 415735

The value based on the local variable will be updated, but the value of Name in lstEmployee having ID as 1 will be unchanged.

That's just not true. The only way that would be true is if Employee is defined as a struct, rather than a class. If you build Employee as a class, the local reference and list reference will both refer to the same object, and when you update the local reference, you also update the object in the list.

Additionally, the following code from your question should not compile:

Employee emp = lstEmployee. Where(emp=>emp.ID==1);

The .Where() method returns an IEnumerable, not an individual object. You need something more like this:

Employee emp = lstEmployee. Where(emp=>emp.ID==1).First();

Upvotes: 2

Related Questions