简体   繁体   中英

Generic function that takes an object and a member name as parameters?

Is there a way to create a generic function that can take an object as a parameter and also one of it's members. So that I could do something like this:

Sort(List<inventory>, inventoryClass.count);

//Do something to display the inventory items sorted by their count member

Sort(List<inventory>, inventoryClass.price);

//Do something to display the inventory items sorted by price.

Then later on even use it on lists of different objects and different members.

How would this function look? How could I use a variable to decide which member I am looking at to sort?

One way to build that is to have the second parameter be a selector function - a Func<inventory,object> that receives the object in question and returns the property to sort by.

List<inventory> Sort(List<inventory> list, 
                     Func<inventory, object> orderBySelector)
{
    return list.OrderBy(orderBySelector).ToList();
}

and then you'd call it by passing an anonymous function, usually a lamba expression:

var listSortedByPrice = Sort(originalList, item => item.price);
var listSortedByCount = Sort(originalList, item => item.count);

Of course, with the minimal amount of work that the Sort function does, you'd be better off just using LINQ's OrderBy directly.

You can pass a Func<TItem, TField> . In Sort you can use it like this:

Sort<TItem, TField>(List<TItem> list, Func<TItem, TField> func)
{
    var field = func(list[0]);
}

and you call Sort like this:

Sort(yourList, item => item .count);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM