Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing a function to filter a list of a items by a property on it's base type in c#

Tags:

c#

types

linq

Lets say we have some types defined as so:

public class BaseClass
{
    public int Value { get; set; }
}

public class SubClassA : BaseClass
{
    public bool SomeBoolValue { get; set; }
}

public class SubClassB : BaseClass
{
    public decimal SomeDecimalValue { get; set; }
}

And we construct two lists of the sub class type like this

List<SubClassA> subClassAList = new List<SubClassA>
{
    new SubClassA {SomeBoolValue = true, Value = 0},
    new SubClassA {SomeBoolValue = true, Value = 2},
    new SubClassA {SomeBoolValue = false, Value = 1},

};

List<SubClassB> subClassBList = new List<SubClassB>
{
    new SubClassB {SomeDecimalValue = 1.3M, Value = 2},
    new SubClassB {SomeDecimalValue = 3.5M, Value = 1},
    new SubClassB {SomeDecimalValue = 0.2M, Value = 5},
};

Is there a way we can implement a function that can can filter both subClassAList and subClassBList on the Value property? I know this can be achieved through casting the results of a function like so:

    public static IEnumerable<BaseClass> OrderList(IEnumerable<BaseClass> list)
    {
        return list.OrderBy(x => x.Value);
    }

...
...

        orderedAList = OrderList(subClassAList)
            .Cast<SubClassA>() //Don't like requiring a cast. Unsafe.
            .ToList();

But then we need to cast the results to get it back into the subclass list which doesn't seem very typesafe. I know the ordering operation in itself is very simple and it probably doesn't warrant a separate function to do the action, but if you were trying to do something more complex than ordering, it would be helpful to contain the logic to a single function/class/whatever in order to do achieve it rather than copying code.

like image 500
eltommo Avatar asked Oct 19 '22 00:10

eltommo


1 Answers

You could accomplish this using a generic method.

public static IEnumerable<T> OrderList<T>(IEnumerable<T> list) where T : BaseClass
{
return list.OrderBy(x => x.Value);
}
like image 73
Max Hampton Avatar answered Oct 20 '22 23:10

Max Hampton