C#uses Objects Comparator for object comparison

C#uses Objects Comparator for object comparison

Objects Comparer is a tool for object comparison. Common data structures in C#can be compared using this three-party library, and more complex objects can also be compared.

最后更新 7/15/2022 9:55 PM
黑哥聊dotNet
预计阅读 5 分钟
分类
.NET
标签
.NET C#

introduced

Objects Comparer是用于对象比较的工具,C#常见的数据结构都是可以用这个三方库进行对比,比较复杂的对象也是可以比较的。

简而言之,Objects Comparer 是一个对象到对象的比较器,它允许逐个成员递归得比较对象,并为某些属性、字段或类型定义自定义比较规则。

installation

nuget 搜索ObjectsComparer

use

First we define a simple class:

public class UserInfomation
{
    public string Name { get; set; }
    public int Age { get; set; }
    public string Sex { get; set; }
}

实例化两个UserInfomation对象并赋不同的值,再实例化 ObjectsComparer.Comparer比较器:

var comparer1 = new ObjectsComparer.Comparer<UserInfomation>();

然后我们将实例化的两个对象传入到 ObjectsComparer.Comparer 方法中:

IEnumerable<Difference> differences1;
var isEqual1 = comparer1.Compare(userInfomationOld, userInfomationNew, out differences1);

Then we use the return values to determine whether the objects are consistent. If they are inconsistent, we can get inconsistent values through differences1.

Looking at the output, you can see that the values of the age attribute of the two instanced objects are different:

那我们再试试List<T>类型的:

List<UserInfomation> lstUserInfomationsOld=new List<UserInfomation>();
for (int i = 0; i < 3; i++)
{
    UserInfomation user=new UserInfomation();
    user.Name = "张三";
    user.Age = 30;
    user.Sex = "男";
    lstUserInfomationsOld.Add(user);
}
List<UserInfomation> lstUserInfomationsNew = new List<UserInfomation>();
for (int i = 0; i < 2; i++)
{
    UserInfomation user = new UserInfomation();
    user.Name = "李四";
    user.Age = 30;
    user.Sex = "男";
    lstUserInfomationsNew.Add(user);
}


var comparer = new ObjectsComparer.Comparer<List<UserInfomation>>();
IEnumerable<Difference> differences;
var isEqual = comparer.Compare(lstUserInfomationsNew, lstUserInfomationsOld, out differences);
string differencesMsg = string.Join(Environment.NewLine, differences);
Console.WriteLine(differencesMsg);

Looking at the output, you can see that it is a problem with inconsistent quantities:

application scenarios

Anyone who has done. NET client development knows that we can't avoid editing data when maintaining some basic data!

Sometimes we open the edit page and the data has not been actually modified. Then we click the Save button to compare whether the data has been modified one by one, or we can directly use brute force without verifying whether the data has been modified, and directly call the update interface.

Then our Objects Comparator comes in handy. We first encapsulate a BaseForm, and then encapsulate a comparison method in the base class control:

protected Result ComPare<T>(T t, T s)
{
    Result result =new Result();
    var comparer = new ObjectsComparer.Comparer<T>();
    IEnumerable<Difference> differences;
    bool isEqual = comparer.Compare(t, s, out differences);
    result.IsEqual = isEqual;
    if (!isEqual)
    {
        string differencesMsg = string.Join(Environment.NewLine, differences);
        result.Msg=differencesMsg;
    }
    return result;
}

public class Result
{
    public bool IsEqual { get; set; }
    public string Msg { get; set; }
}

When we open the edit page, we will load the data of the current page. At this time, we can get the data before editing and set it as a global variable. Then when saving, we can get the edited object. At this time, we can call the base class's comparison method.

Get whether the value between the two objects has changed. If there is no change, we will give hints such as "The data has not been modified. Do you want to close the form":

public partial class MainFrm : BaseForm
{
    Test _testOld;
    public MainFrm()
    {
        InitializeComponent();
        _testOld = LoadData();
        txtName.Text= _testOld.Name;
        txtAge.Text = _testOld.Age.ToString();
        txtSex.Text = _testOld.Sex;
    }
    private Test LoadData()
    {
        Test test = new Test();
        test.Name = "张三";
        test.Age = 30;
        test.Sex = "男";
        return test;


    }


    private void uiButton1_Click(object sender, EventArgs e)
    {
        Test test=new Test();
        test.Name =txtName.Text;
        test.Age =int.Parse( txtAge.Text);
        test.Sex=txtSex.Text;
            Result result=  ComPare(_testOld, test);
        if (result.IsEqual)
        {
            MessageBox.Show("数据未修改");
            return;
        }
        //然后再写保存逻辑
        MessageBox.Show("保存成功");
    }
}
public class Test
{
    public string Name { get; set; }
    public int Age { get; set; }
    public string Sex { get; set; }
}

Of course, there are many application scenarios, I just share the scenarios I often use.

Finally, I hope you will share more useful tools with neter to jointly improve the net environment!

Keep Exploring

延伸阅读

更多文章
同分类 / 同标签 4/22/2026

Support for. NET by operating system versions (250707 update)

Use virtual machines and test machines to test the support of each version of the operating system for. NET. After installing the operating system, it is passed by measuring the corresponding running time of the installation and being able to run the Stardust Agent.

继续阅读
同分类 / 同标签 2/7/2026

Summary of experience in using AOT

From the very beginning of project creation, you should develop a good habit of conducting AOT release testing in a timely manner whenever new features are added or newer syntax is used.

继续阅读