Easy get/set of denormalized list of strings - messy solution to triggering `set`

102 views Asked by At

I'm denormalizing a one-to-many into a List<int>:

    public string DbUsersMessaged { get; set; }
    public List<int> UsersMessaged {
        get {
            return string.IsNullOrEmpty(DbUsersMessaged) ? new List<int>() : DbUsersMessaged.Split(',').Select(Int32.Parse).ToList();
        }
        set {
            DbUsersMessaged = value != null ? String.Join(",", value) : null;
        }
    }

To read, I can query UsersMessaged.Contains(id).

To write, I'd like to simply do UsersMessaged.Add(id), but this doesn't work because set isn't called.

For now, I'm doing this to trigger the set:

  UsersMessaged = UsersMessaged.AddReassign(user);
  public static List<int> AddReassign(this List<int> list, int item)
    {
        var tempList = list;
        if (list.Contains(item))
            return list;
        tempList.Add(item);
        list = tempList;
        return list;
    }

But this is awful because next week I'll forget that I can't just do Add and waste a bunch of time remembering this crap. What's a cleaner way to go about setting a denormalized List<T>?

1

There are 1 answers

3
Camilo Terevinto On BEST ANSWER

A cleaner way to do this is to implement your own List and override the Add method

public class DbList : List<int>
{
    public override void Add(int value)
    {
        //perform your logic here.
    }
}

And you can have your string value in the DbList instance.