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
然后,我们使用 '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' 进行去重后,只有两个元素被保留下来,其他两个元素被认为是重复的。
AI 优化版
原文地址:https://www.cveoy.top/t/topic/mXRg 著作权归作者所有。请勿转载和采集!