Here's the full example. Not really sure what you're trying to do with numChocolates, but the rest of it illustrates passing in the order by expression. Note how it handles any type, such as int, string, double. It was interesting to figure out the nuance of this.
using System;
using System.Collections.Generic;
using System.Linq;
namespace CPDemo
{
class Person
{
public int Age { get; set; }
public string LastName { get; set; }
public string FirstName { get; set; }
public double Distance { get; set; }
public override string ToString()
{
return $"{LastName}, {FirstName}, {Age}, {Distance}";
}
}
class Program
{
static void Main(string[] args)
{
var people = new List<Person>()
{
new Person() {Age = 50, LastName = "Shmo", FirstName = "Joe", Distance = 10 },
new Person() {Age = 40, LastName = "Doe", FirstName = "Jane", Distance = 5 },
new Person() {Age = 30, LastName = "Willard", FirstName = "Willy", Distance = 1 }
};
Console.WriteLine("By age:");
DistributeChocolates(people, 5, x => x.Age);
Console.WriteLine();
Console.WriteLine("By last name:");
DistributeChocolates(people, 5, x => x.LastName);
Console.WriteLine();
Console.WriteLine("By distance:");
DistributeChocolates(people, 5, x => x.Distance);
}
static void DistributeChocolates<T>(IEnumerable<Person> people, int numChocolates, Func<Person, T> sorter)
{
var toPeople = people.OrderBy(sorter);
Ship(toPeople, numChocolates);
}
static void Ship(IEnumerable<Person> people, int numChocolates)
{
foreach (Person person in people)
{
Console.WriteLine(person.ToString());
}
}
}
}
This is the output:
By age:
Willard, Willy, 30, 1
Doe, Jane, 40, 5
Shmo, Joe, 50, 10
By last name:
Doe, Jane, 40, 5
Shmo, Joe, 50, 10
Willard, Willy, 30, 1
By distance:
Willard, Willy, 30, 1
Doe, Jane, 40, 5
Shmo, Joe, 50, 10