在C#中,检查重复项通常涉及到比较对象的某些字段是否相等。以下是一个通用的C#函数示例,它可以用于检查不同对象中的不同字段是否存在重复项。这个函数使用了泛型和反射来实现灵活性。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
public static class DuplicateChecker
{
public static bool ContainsDuplicate<T>(IEnumerable<T> items, params string[] fieldNames)
{
if (items == null || !fieldNames.Any())
return false;
var seen = new HashSet<string>();
foreach (var item in items)
{
var key = GenerateKey(item, fieldNames);
if (!seen.Add(key))
return true; // 发现重复项
}
return false; // 没有发现重复项
}
private static string GenerateKey<T>(T item, string[] fieldNames)
{
var keyParts = new List<string>();
foreach (var fieldName in fieldNames)
{
var propertyInfo = typeof(T).GetProperty(fieldName);
if (propertyInfo == null)
throw new ArgumentException($"No property named '{fieldName}' on type '{typeof(T).Name}'");
var value = propertyInfo.GetValue(item)?.ToString();
keyParts.Add(value ?? string.Empty);
}
return string.Join("|", keyParts);
}
}
HashSet
来快速检测重复项。ContainsDuplicate<T>
可以接受任何类型的集合。GenerateKey
方法根据指定的字段生成唯一的键。假设有一个Person
类,我们想要检查是否有重复的FirstName
和LastName
组合:
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
}
var people = new List<Person>
{
new Person { FirstName = "John", LastName = "Doe", Age = 30 },
new Person { FirstName = "Jane", LastName = "Doe", Age = 28 },
new Person { FirstName = "John", LastName = "Doe", Age = 30 } // 重复项
};
bool hasDuplicate = DuplicateChecker.ContainsDuplicate(people, "FirstName", "LastName");
Console.WriteLine(hasDuplicate); // 输出: True
PropertyInfo
对象来优化。通过这种方式,你可以创建一个强大且灵活的工具来检查不同对象中的重复项。
领取专属 10元无门槛券
手把手带您无忧上云