C# Aynı Tipteki İki Classın Propertyleri Karşılaştırma

Aynı tipteki iki class’ın property değerlerinin aynı olup olmadığını kontrol eder.

public static bool ArePropertiesEqual<T>(T item, T source, params string[] excludedProperties) where T : new()
        {
            if (item != null && source != null)
            {
                Type type = typeof(T);

                foreach (var prop in type.GetProperties())
                {
                    if (excludedProperties != null && excludedProperties.Contains(prop.Name))
                    {
                        continue;
                    }

                    var itemValue = prop.GetValue(item);
                    var sourceValue = prop.GetValue(source);

                    if (itemValue == null && sourceValue == null)
                    {
                        continue;
                    }
                    else if (itemValue == null || sourceValue == null)
                    {
                        return false;
                    }
                    else if (prop.PropertyType == typeof(string) || ((dynamic)prop.PropertyType).IsValueType == true)
                    {
                        if (!itemValue.Equals(sourceValue))
                        {
                            return false;
                        }
                    }
                    else
                    {
                        string itemValueJson = JsonHelper.Serialize(itemValue);
                        string sourceValueJson = JsonHelper.Serialize(sourceValue);

                        if (!string.Equals(itemValueJson, sourceValueJson))
                        {
                            return false;
                        }
                    }
                }

                return true;
            }
            else
            {
                return false;
            }
        }

Leave a Reply