首页 > 解决方案 > 用于检查重复项(不同对象、不同字段)的通用 C# 函数

问题描述

我想创建一个通用函数,它获取三个参数(对象列表、属性名称和值)......该函数必须检查重复项。所以 :

class A  {
   public string description;
   public string abbreviation;
}

class B {
   public string description;
   public string name;
}

我有两个 List 对象...一个具有多个 A 类对象,一个具有多个 B 类对象。

List <A> listOfA
List <B> listOfB

我想要一个这样的函数:

bool hasDuplicateAbbreviation = CheckDuplicate (listOfA, "abbreviation", "ALG");
bool hasDuplicateName = CheckDuplicate (listOfB, "name", "Mrs. Smith");
bool hasDuplicateDescription = CheckDuplicate (listOfB, "description", "Nice toolkit");

我该怎么做?

如果相同的函数也可以用于具有整数等级的 C 类,那就太好了:

class C  {
   public string description;
   public int rank;
}

List <C> listOfC

bool hasDuplicateRank = CheckDuplicate (listOfC, "rank", 2);

标签: c#functiongenerics

解决方案


您需要使用反射(需要导入System.Reflection):

public static int CheckDuplicate<T>(IEnumerable<T> input, string field, object value)
{
    int count = 0;
    Type type = typeof(T);
    foreach(var item in input)
    {
        var fieldInfo = type.GetField(field);
        if(fieldInfo!= null)
            if(fieldInfo.GetValue(item) == value) count++;
        else
        {
            var propInfo = type.GetProperty(field);
            if(propInfo != null && propInfo.GetValue(item) == value) count++;
        }
    }
    return count;
}

这将返回给定值重复的次数。

if(CheckDuplicate(a, "abbreviation", "abbr1") > 1)
{
    // there is a duplicate
}

现场演示


推荐阅读