I have the following as a way to denormalize a list of integers:
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 sersMessaged.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 not ideal because I have AddReassign
throughout. Ideally I can just use Add
. Per another answer, I know I can override the Add
method via the following:
public class DbList : List<int>
{
public override void Add(int value)
{
// AddReassign logic goes here
}
}
However I have some questions:
- How can I move my logic into the overridden
Add
? I've been struggling with syntax for a while. - How would
get
change in the above? I know I need to return aDbList
, but how do I cleanly instantiate aDbList
from anIEnumerable
? - Is there any simple way to make this solution generic, instead of just for
int
?