0

I have two objects.

public class GlobalSettings
{
    public bool A { get; set; }
    public bool B { get; set; }
    public bool C { get; set; }
    public bool D { get; set; }
}

public class UserSettings
{
    public bool A { get; set; }
    public bool B { get; set; }
    public bool C { get; set; }
    public bool D { get; set; }
}

I need to compare these two objects. Depend on the property values of GlobalSettings i need to remove the property from UserSettings.

For eg.

From GlobalSettings property A value is false means i want to remove that property from UserSettings. Then i need to remove propery A from UserSettings like below.

public class UserSettings
{
    public bool B { get; set; }
    public bool C { get; set; }
    public bool D { get; set; }
}

Is it possible to do this linq?

3 Answers3

1

If you really wanted to automate this you could using Linq and reflection - e.g.

  var query = from aProp in a.GetType().GetProperties()
              let aValue = aProp.GetValue(a)
              let bProp = b.GetType().GetProperty(aProp.Name)
              let bValue = bProp.GetValue(b)
              where !aValue.Equals(bValue)
              select new { aProp.Name, aValue, bValue };

  var allTheSame = !query.Any();
Stuart
  • 66,722
  • 7
  • 114
  • 165
1

Given the 'Remove' part of your question, I think you will be much better off using a Dictionary rather than a Type for your settings.

You can't remove properties from normal static C# Types, but you can easily remove entries from Dictionaries using the Remove(key) method.

Stuart
  • 66,722
  • 7
  • 114
  • 165
0

Try something like this: UserSettings inherits from GlobalSettings and in this example, if you use UserSettings.A, if will check if that is false in its parent class, and use UserSettings.A if it is false, and GlobalSettings.A if it's true.

public class GlobalSettings
{
    public virtual bool A { get; set; }
}

public class UserSettings : GlobalSettings
{
    public override bool A 
    { 
        get 
        { 
            return base.A  ? base.A : A;
        }
        set
        {
            this.A = value;
        }
    }
}
Colm Prunty
  • 1,595
  • 1
  • 11
  • 29