以下是一个使用LINQ比较两个列表的示例,每个列表都包含在一个对象内,至少有一个相等的情况。
假设我们有一个名为Person的类,每个Person对象包含一个名字和一个兴趣列表。我们要比较两个Person对象列表,找到具有至少一个相同兴趣的Person对象。
首先,我们定义Person类:
public class Person
{
public string Name { get; set; }
public List Interests { get; set; }
}
然后,我们创建两个Person对象列表,并添加一些示例数据:
List list1 = new List
{
new Person { Name = "Alice", Interests = new List { "Reading", "Gardening" } },
new Person { Name = "Bob", Interests = new List { "Cooking", "Hiking" } },
new Person { Name = "Charlie", Interests = new List { "Swimming", "Gardening" } }
};
List list2 = new List
{
new Person { Name = "Dave", Interests = new List { "Hiking", "Travelling" } },
new Person { Name = "Eve", Interests = new List { "Painting", "Reading" } },
new Person { Name = "Frank", Interests = new List { "Cooking", "Swimming" } }
};
接下来,我们可以使用LINQ查询来比较两个列表,并找到具有至少一个相同兴趣的Person对象:
var result = from p1 in list1
from p2 in list2
where p1.Interests.Intersect(p2.Interests).Any()
select new { Person1 = p1, Person2 = p2 };
foreach (var pair in result)
{
Console.WriteLine($"{pair.Person1.Name} and {pair.Person2.Name} have at least one common interest.");
}
运行以上代码,输出将是:
Alice and Eve have at least one common interest.
Bob and Frank have at least one common interest.
Charlie and Bob have at least one common interest.
Charlie and Frank have at least one common interest.
这样,我们使用LINQ成功比较了两个列表,并找到了具有至少一个相同兴趣的Person对象。