C# 使用DistinctBy 实现多个条件重复验证
在C#中,可以使用DistinctBy方法来实现多个条件的重复验证。DistinctBy方法用于按照指定的条件对集合进行去重操作。
下面是一个示例代码,演示如何使用DistinctBy方法实现多个条件的重复验证:
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main(string[] args)
{
List<Person> persons = new List<Person>
{
new Person { Name = "John", Age = 25 },
new Person { Name = "John", Age = 30 },
new Person { Name = "Jane", Age = 25 },
new Person { Name = "Jane", Age = 30 }
};
var distinctPersons = persons.DistinctBy(p => new { p.Name, p.Age });
foreach (var person in distinctPersons)
{
Console.WriteLine($"Name: {person.Name}, Age: {person.Age}");
}
}
}
class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
在上面的代码中,我们定义了一个Person类,包含Name和Age属性。我们创建了一个名为persons的List<Person>集合,并添加了四个元素。
然后,我们使用DistinctBy方法对persons集合进行去重操作,指定了两个条件:Name和Age。通过使用匿名类型来表示多个条件,我们可以确保只有在Name和Age都相同时,才会被认为是重复元素。
最后,我们使用foreach循环遍历去重后的集合,并打印每个元素的Name和Age属性。
运行上面的代码,输出结果如下:
Name: John, Age: 25
Name: John, Age: 30
Name: Jane, Age: 25
Name: Jane, Age: 30
可以看到,根据Name和Age进行去重后,只有两个元素被保留下来,其他两个元素被认为是重复的。
原文地址: https://www.cveoy.top/t/topic/i4Tg 著作权归作者所有。请勿转载和采集!