如何在 C# 中的组合中找到最佳匹配

How to find a best match among combinations in C#

假设我有一个包含 5 个属性的集合。

我的输入: A=1;B=2;c=3;d=4;

使用这个输入我必须得到 属性 E(它正好接近我的输入或接近我的输入)

在这种情况下,我的预期结果是

结果 A 和结果 C。

所以应该检查代码中的以下组合

if(A and B and C and D) all matches collection 
    take that;
    break;
else if(A and B and C) matches the collection
    take that;
    break;
else if (A and B and D) matches the collection 
    take that;
    break;
else if (A and B and D) matches the collection 
    take that;
else if (A and B) matches the collection 
    take that;
    break;
else if(A and C) matches the collection
    take that;
    break;
else if(A and D) matches the collection
    take that;
    break;
else if A matches the collection
    takethat;
    break;
else if B matches the collection
    take that;
    break;
else if c matches the collection
    take that;
    break;
else if D matches the collection
    take that;
    break;
else
    "No Match Found"

所以当要检查的属性数量越多时,我们需要构建的组合就越多。所以我需要创建一个实用程序来动态构建组合并检查对象的比较。我可以将属性作为字符串数组传递,并可以进行所需的组合,但我不知道如何访问对象属性。
如何处理这种情况?

您可以在 class 中定义自定义函数,例如:

public class CustomObject
{
    public CustomObject(string p1, string p2, string p3, string p4)
        : this(p1,p2,p3,p4,null)
    {
    }

    public CustomObject(string p1, string p2, string p3, string p4, string p5)
    {
        Prop1 = p1;
        Prop2 = p2;
        Prop3 = p3;
        Prop4 = p4;
        Prop5 = p5;
    }

    public string Prop1 {get;set;}
    public string Prop2 {get;set;}
    public string Prop3 {get;set;}
    public string Prop4 {get;set;}
    public string Prop5 {get;set;}

    public int NumberOfSameProps(CustomObject other)
    {
        return (Prop1 == other.Prop1 ? 1 : 0) +
               (Prop2 == other.Prop2 ? 1 : 0) +
               (Prop3 == other.Prop3 ? 1 : 0) +
               (Prop4 == other.Prop4 ? 1 : 0);
    }
}

然后你所要做的就是获取比较 returns 最大值的项目。

用法:

CustomObject obj1 = new CustomObject("1","2","3",null,"Result A");
CustomObject comp = new CustomObject("1","2","3","4");
int nb = obj1.NumberOfSameProps(comp); // returns 3