mardi 28 février 2023

How do I remove elements from multiple Lists that are properties of a generic object using reflection?

I have a generic object that could have mulitple Lists as properties.

How do I remove elements from those lists generically using reflection?

Let's say I have objects that are like below

public class ObjectA
{
    public List<long> listA
    public List<string> listB
}

public class ObjectB
{
    public List<int> listC
    public List<decimal> listD
}

How would I go about adding and removing elements from those lists generically?

Here's what I thought of, but it's wrong:

private bool PropertyIsGenericList(PropertyInfo property)
        {
            return property.PropertyType.IsGenericType && typeof(IList).IsAssignableFrom(property.PropertyType);
        }

private void RemoveElementsFromPropertyThatAreLists(object dto)
        {
            foreach (PropertyInfo property in dto.GetType().GetProperties())
            {
                if (dto != null && property != null && PropertyIsGenericList(property))
                {
                    RemoveElementsFromList(property, globalIndex); // Don't know what to pass to this
                }

            }
        }

protected void RemoveElementsFromList<ListType>(List<ListType>? columns, int? startingIndex = null)
        {
            startingIndex = startingIndex != null ? startingIndex.Value : globalIndex;
            if (columns != null)
            {
                for (int columnIndex = columns.Count - 1; startingIndex <= columnIndex; columnIndex--)
                {
                    columns.RemoveAt(columnIndex);
                }
            }
        }




Aucun commentaire:

Enregistrer un commentaire