user3610920
user3610920

Reputation: 1642

How to find a best match among combinations in C#

Say I have a collection which has 5 properties.

enter image description here

My Input: A=1;B=2;c=3;d=4;

Using this input i have to get the Property E ( which is exactly close to my input or nearly close to my input)

In this case my expected result is enter image description here

Result A and Result C.

So should check the below combinations in code

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"

So when the number of properties to check is more , the more combinations we need to build . So i need to create a utility which build the combinations dynamically and check the comparison of objects. I can pass the properties as string array and can make the required combinations, but i have no clue how to access the object properties.
How to handle this situation ?

Upvotes: 0

Views: 436

Answers (1)

Rafalon
Rafalon

Reputation: 4515

You can define a custom function in your class like:

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);
    }
}

And then all you have to do is get the items where the comparison returns the maximum value.

Usage:

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

Upvotes: 1

Related Questions