0

I have following classes. I want keep BP value unique across all items of Admin_Fee_Prop. I don't know what collection type of property Admin_Fee_Prop should be used or how to define Admin_Fee Class so that BP property value should remain unique across all item of Admin_Fee_Prop? Some times i may also need uniqueness on composite properties.

Public Class BE
{
  public string Name {get;set:)
  public List<Admin_Fee> Admin_Fee_Prop {get;set:) 
}

public class Admin_Fee
    {
        public string BP_Name { get; set; }

        public int BP { get; set; }

        public int BP_Perc { get; set; }

}

2 Answers2

1

Define BP property as Guid instead of int. Call Guid.NewGuid() to generate new and unique value.

If you want to instantiate it every time Admin_Fee_Prop is created, add a default constructor that would generate a new value for BP. Also, you can store Admin_Fee_Prop in a Dictionary where Key would be Admin_Fee_Prop.BP, and value would be an object of type Admin_Fee_Prop.

Huske
  • 9,186
  • 2
  • 36
  • 53
0

Use a HashSet<Admin_Fee>, and implement Equals and GetHashCode in Admin_Fee so that two instances of Admin_Fee are considered equal if the have the same BP value:

public Class BE
{
    public string Name {get;set:)
    public HashSet<Admin_Fee> Admin_Fee_Prop {get;set:) 
}


public class Admin_Fee
{
    public string BP_Name { get; set; }
    public int BP { get; set; }
    public int BP_Perc { get; set; }

    public override bool Equals(object other)
    {
        if (!(other is Admin_Fee))
            return false;
        return this.BP == ((Admin_Fee)other).BP;
    }

    public override int GetHashCode()
    {
        return BP;
    }

}

Another possible approach is to implement an IEqualityComparer<Admin_Fee>, and pass it as a parameter to the HashSet<Admin_Fee> constructor.

Some times i may also need uniqueness on composite properties

In that case you need to take all these properties into account in Equals and GetHashCode. For examples of how to generate a hashcode from several properties, have a look at this answer.

Community
  • 1
  • 1
Thomas Levesque
  • 286,951
  • 70
  • 623
  • 758