以下是一个使用C#比较两个属性列表并将差异添加到第三个列表的示例代码:
using System;
using System.Collections.Generic;
public class Property
{
public string Name { get; set; }
public string Value { get; set; }
}
class Program
{
static void Main(string[] args)
{
List list1 = new List()
{
new Property { Name = "Name1", Value = "Value1" },
new Property { Name = "Name2", Value = "Value2" },
new Property { Name = "Name3", Value = "Value3" }
};
List list2 = new List()
{
new Property { Name = "Name1", Value = "Value1" },
new Property { Name = "Name4", Value = "Value4" },
new Property { Name = "Name5", Value = "Value5" }
};
List diffList = CompareLists(list1, list2);
Console.WriteLine("Differences:");
foreach (var property in diffList)
{
Console.WriteLine("Name: {0}, Value: {1}", property.Name, property.Value);
}
}
static List CompareLists(List list1, List list2)
{
List diffList = new List();
foreach (var property1 in list1)
{
bool found = false;
foreach (var property2 in list2)
{
if (property1.Name == property2.Name && property1.Value == property2.Value)
{
found = true;
break;
}
}
if (!found)
{
diffList.Add(property1);
}
}
return diffList;
}
}
这个示例中,我们创建了一个Property
类,它有两个属性Name
和Value
。然后我们创建了两个Property
类的列表list1
和list2
。我们使用CompareLists
函数比较这两个列表,并将差异添加到名为diffList
的第三个列表中。最后,我们遍历diffList
并打印差异。运行这个示例,我们会得到以下输出:
Differences:
Name: Name2, Value: Value2
Name: Name3, Value: Value3
下一篇:比较两个数值变量通过两个分组