-1

I have a prop List<User> Users and I want to get the User that has the specified id without getting the reference to it.
In UserDAO:

public User ReturnUser(int id)
{
    var q = this.Users.Where(x => x.Id == id);
    return q.ToList()[0];
}

In main:

User newUser = ud.ReturnUser(0);

Console.WriteLine(newUser.Name);
newUser.Name = "john";
Console.WriteLine(ud.Users[0].Name);
Rômulo Borges
  • 127
  • 1
  • 3
  • 9

4 Answers4

1

If your User object contains only primitive properties, you could add this method:

public User ShallowCopy(){
  return (User)this.MemberwiseClone();
}

And then do this:

//note: no error handling if ID not found
public User ReturnUser(int id)
{
  return this.Users.Single(x => x.Id == id).ShallowCopy();

}

If your user contains complex type properties, you'd have to implement a deep copy if you didn't want those properties to just be references

The fine manual has a reasonable amount to say and some good examples

Caius Jard
  • 72,509
  • 5
  • 49
  • 80
1

First of all use FirstOrDefault() instead of Where() if you are going to take only the first match.

And secondly, you can just return a Clone of the result:

public User ReturnUser(int id)
{
    var q = this.Users.FirstOrDefault(x => x.Id == id);
    return q?.MemberwiseClone();
}
Ashkan Mobayen Khiabani
  • 33,575
  • 33
  • 102
  • 171
0

I think AsNoTracking() might be the way you want to go.

public User ReturnUser(int id)
{
    return this.Users.AsNoTracking().FirstOrDefault(x => x.Id == id);
}

This link has more information on AsNoTracking() but the above should achieve what you're looking to accomplish.

What difference does .AsNoTracking() make?

Dortimer
  • 619
  • 8
  • 25
0

Try This, But be careful this will only work if your user object contains only primitive type such as int, double, bool and not reference types.

For Deep Copy/Deep Clone see this

class Program
{
    static void Main(string[] args)
    {
        var users = new List<User>()
        {
            new User()
            {
                Name = "My Name",
                Job = new Job()
                {
                    Title = "Developer"
                }
            }
        };

        var clonedUser = users[0].Clone();

        clonedUser.Name = "My Updated Name";
        clonedUser.Job.Title = "Graphic Designer"; //This Won't Work

        Console.WriteLine(users[0].Name);
        Console.WriteLine(users[0].Job.Title);
        Console.ReadLine();
    }
}

public class User
{
    public string Name { get; set; }
    public Job Job { get; set; }

    public User Clone()
    {
        return (User) this.MemberwiseClone();
    }
}

public class Job
{
    public string Title { get; set; }
}
Mozart
  • 2,117
  • 2
  • 20
  • 38