Pass property itself to function as parameter in C#

后端 未结 7 1614
春和景丽
春和景丽 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条回答
  •  一生所求
    2020-12-12 19:43

    Just to add from the answers above. You can also do a simple flag for the order direction.

    public class Processor
    {
        public List SortableItems { get; set; }
    
        public Processor()
        {
            SortableItems = new List();
            SortableItems.Add(new SortableItem { PropA = "b" });
            SortableItems.Add(new SortableItem { PropA = "a" });
            SortableItems.Add(new SortableItem { PropA = "c" });
        }
    
        public void SortItems(Func keySelector, bool isAscending)
        {
            if(isAscending)
                SortableItems = SortableItems.OrderBy(keySelector).ToList();
            else
                SortableItems = SortableItems.OrderByDescending(keySelector).ToList();
        }
    }
    

提交回复
热议问题