Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Only set property on one object

Tags:

c#

How can I make a boolean property like a RadioButton? You know, like a RadioButton, only one can be selected?

Like example below.

When I set one Employee IsResponsiblePerson to true, it should set all others to false. Without using a loop.

var list = new ObservableCollection<Employee>();

public class Employee
{
    public string Name{get;set;}
    public string Surname{get;set;}
    public bool IsResponsiblePerson{get;set;}
}
like image 376
user1702369 Avatar asked Sep 07 '17 10:09

user1702369


1 Answers

What i'd probably do if I didn`t want to use loops, is, as Lasse V. Karlsen says in a comment, store instead the name of the "ResponsiblePerson" in another property:

static string ResponsiblePerson {get;set;}

And change the IsResponsiblePerson property to something like this:

public bool IsResponsiblePerson 
{ 
    get 
    { 
        return this.Name == ResponsiblePerson; 
    }
    set 
    {   
        if (value)
        {
             ResponsiblePerson = this.Name;
        }
        else
        {
            if (this.Name == ResponsiblePerson)
            {
                ResponsiblePerson = "";
            }
        }
    }
}

Sample code:

List<Employee> employees = new List<Employee>() { new Employee() { Name = "name1" },
                                                    new Employee() { Name = "name2" },
                                                    new Employee() { Name = "name3" } };

Employee emp1 = employees.Where(x => x.Name == "name1").First();
emp1.IsResponsiblePerson = true;

Employee emp2 = employees.Where(x => x.Name == "name2").First();
emp2.IsResponsiblePerson = true;

foreach (Employee e in employees) 
{ 
     Console.WriteLine(e.IsResponsiblePerson); //false true false
}

I've made a DotNetFiddle sample here

like image 124
5 revs, 4 users 77%SuperG Avatar answered Oct 20 '22 23:10

5 revs, 4 users 77%SuperG