How to find changed property names & values in record types?

644 views Asked by At

Create Record type.

public record Animal
{
  public string Name{ get; init; }
  public string Type{ get; init; }
  public string Genus{ get; init; }
  public string Owner { get; init; }
}

var cat= new Animal
{
  Name = "FluffyCat",
  Type = "Feline",
  Genus = "Mammal",
  Owner = "Agent Smith"
 
};

Clone and change some values.

var newCat = cat with
            { Name = "AngryCat", Owner= "Morpheus" };

We can test for equality easily enough

Console.WriteLine(newCat.Equals(cat));

How can I find the changed values and property names without comparing every property value?

1

There are 1 answers

1
Jawad On BEST ANSWER

Not sure how you can check for changed properties without checking for changed values.

A LINQ query with Reflections can be used to see what property names no longer are the same. This is compact and does not need an if statement for each of the properties.

public record Animal 
{
    public string Name { get; init; }
    public string Type { get; init; }
    public string Genus { get; init; }
    public string Owner { get; init; }

    public Dictionary<string, string> ChangedProps(Animal animal)
    {
        return GetType()
            // Get all the names of object properties
            .GetProperties()

            // Convert to a List to use LINQ
            .Cast<PropertyInfo>()

            // Only get the properties whose values are not the same
            .Where(x => !GetType().GetProperty(x.Name).GetValue(this, null).Equals(GetType().GetProperty(x.Name).GetValue(animal, null)))

            // Create a KVP to add to a dictionary
            .Select(x => new KeyValuePair<string, string>( x.Name, (string)animal.GetType().GetProperty(x.Name).GetValue(animal, null) ))

            // Convert all the items that dont match into a dictionary
            .ToDictionary(x => x.Key, x => x.Value);
    }
}

This will return a Dictionary of Keys and Values that are changed.