Pass property itself to function as parameter in C#

后端 未结 7 1629
春和景丽
春和景丽 2020-12-12 19:25

I am looking for a method to pass property itself to a function. Not value of property. Function doesn\'t know in advance which property will be used for sorting. Simplest w

7条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-12 19:57

    You can pass a property accessor to the method.

    List SortBy(List toSort, Func getProp)
    {
        if (toSort != null && toSort.Count > 0) {
            return toSort
                .OrderBy(x => getProp(x))
                .ToList();
        }
        return null;
    }
    

    You would call it like this:

    var result = SortBy(toSort, x => x.maxSpeed);
    

    But you could go one step further and write your own extension method.

    public static class CollectionExtensions
    {
        public static List OrderByAsListOrNull(
            this ICollection collection, Func keySelector)
    
            if (collection != null && collection.Count > 0) {
                return collection
                    .OrderBy(x => keySelector(x))
                    .ToList();
            }
            return null;
        }
    }
    

    Now you can sort like this

    List sorted = toSort.OrderByAsListOrNull(x => x.maxSpeed);
    

    but also

    Person[] people = ...;
    List sortedPeople = people.OrderByAsListOrNull(p => p.LastName);
    

    Note that I declared the first parameter as ICollection because it must fulfill two conditions:

    1. It must have a Count property
    2. It must be an IEnumerable in order to be able to apply the LINQ method OrderBy.

    List is an ICollection but also an array Person[] as many other collections.


    So far, I have shown how you can read a property. If the method needs to set a property, you need to pass it a setter delegate as well

    void ReadAndWriteProperty(Func getProp, Action setProp)
    

    Where T is the type of the property.

提交回复
热议问题