dimanche 13 mai 2018

How can you drop items in a `ICollection` without knowing its `TSource`?

How can you drop items in a ICollection without knowing its TSource? I thought LINQ would be the best route for this, but I cannot figure out how it might be done with Reflection or any other method.

I am trying to implement this in a class that inherits System.Attribute so generic types are not permitted.

private int _maxLength = -1;

protected override object MutateValue(object value, IMutationContext context)
{
    if (value != null) {
        if (
            value is string valueAsString &&
            (
                _maxLength > -1 || TryGetStringLengthAttributeValue(context, out _maxLength)
            ) &&
            valueAsString.Length > _maxLength
        ) {
            value = valueAsString.Substring(0, _maxLength);
        }
        else if (
            value is ICollection valueAsCollection &&
            (
                _maxLength > -1 || TryGetMaxLengthAttributeValue(context, out _maxLength)
            ) &&
            valueAsCollection.Count > _maxLength
        ) {
            // Error CS1061
            value = valueAsCollection.Take(_maxLength);
        }
    }

    _maxLength = -1;

    return value;
}

You will see this code will not compile and throws this error:

Error CS1061: 'ICollection' does not contain a definition for 'Take' and no extension method 'Take' accepting a first argument of type 'ICollection' could be found (are you missing a using directive or an assembly reference?)





Aucun commentaire:

Enregistrer un commentaire