How to sum up properties' values from datamember in C#?

53 views Asked by At

I have an event class defined as the following:

[Serializable]
[DataContract]
public class BaseEvent
{
    [DataMember]
    public int count { get; set; }

    [DataMember]
    public SubEventClass SubEventClass { get; set; }
}

and a SubEventClass defined as the following:

[Serializable]
[DataContract]
public class SubEventClass
{
    [DataMember]
    public int Width { get; set; }

    [DataMember]
    public long Length { get; set; }

    [DataMember]
    public long Area { get; set; }
}

I expected to merge/sum two BaseEvent objects values by calling this method:

public static BaseEvent MergeQueryShapeStats(BaseEvent obj1, BaseEvent obj2)
{
    obj1.count += obj2.count;

    var properties = typeof(SubEventClass).GetProperties();

    foreach (var prop in properties)
    {
        var value = prop.GetValue(obj2.SubEventClass, null);

        if (value != null)
            prop.SetValue(obj1.SubEventClass, value, null);
    }

    return obj1;
}

This following code, to my knowlege, just sets values from obj2 to obj1:

prop.SetValue(obj1.SubEventClass, value, null);

Does anybody know how to sum values of obj2 and reset obj1?

Thanks

2

There are 2 answers

0
Deritha On

Oh. It's resolved by the following change:

  1. change the prop type to long in SubEventClass

  2. call this method:

       public static BaseEvent MergeQueryShapeStats(BaseEvent obj1, BaseEvent obj2)
        {
            obj1.count += obj2.count;

            var properties = typeof(SubEventClass).GetProperties();

            foreach (var prop in properties)
            {
                var value2 = prop.GetValue(obj2.SubEventClass, null);

                if (value2 != null)
                {
                    var value1 = prop.GetValue(obj1.SubEventClass, null);
                    prop.SetValue(obj1.SubEventClass, long.Parse(value1.ToString()) + long.Parse(value2.ToString()), null);
                }
            }

            return obj1;
        }
2
Leandro Bardelli On

There is no need to get the types of the properties if you already know the object.

If there is no solution in your method to resolve the null value, you should check the null before pass the obj1 and obj2

 public static BaseEvent MergeQueryShapeStats(BaseEvent obj1, BaseEvent obj2)
    {
        return new BaseEvent() {
            count = obj1.count + obj2.count,
            SubEventClass  = new SubEventClass() {
                Width = obj1.SubEventClass.Width  + obj2.SubEventClass.Width,
                Length = obj1.SubEventClass.Length + obj2.SubEventClass.Length ,
                Area = obj1.SubEventClass.Area + obj2.SubEventClass.Area   

            }
        };
    }