I have a class, Container
which has many IReadOnlyList<(string, int)>
properties on it.
It also has a TotalCount
property which is the total count of ALL these lists.
Of course I could simply return list1.Count + list2.Count … but I wanted to see if I could do it more compactly using TypeDescriptor
and PropertyDescriptor
.
The problem seems to be that the listProperties
variable is not right, but I don't know what I am doing wrong?
Could someone help identify what I am doing wrong please?
Here is my code:
public class Container
{
public IReadOnlyList<(string name, int id)> List1 { get; set; } = new List<(string, int)>();
public IReadOnlyList<(string code, int id)> List2 { get; set; } = new List<(string, int)>();
// Lots of other Lists of type IReadOnlyList<(string, int)>
// ....
public int TotalCount
{
get
{
var allProperties = TypeDescriptor.GetProperties(this).Cast<PropertyDescriptor>();
var listProperties = allProperties.Where(p => p.PropertyType is IReadOnlyList<(string, int)>).ToList();
var total = listProperties.Sum(pd => (int)pd.GetValue(this));
return total;
}
}
}
Aucun commentaire:
Enregistrer un commentaire