Skip to content

Instantly share code, notes, and snippets.

@Zegis
Created September 1, 2016 11:14
Show Gist options
  • Save Zegis/797e48116dfdc520c990a86cfb0f8712 to your computer and use it in GitHub Desktop.
Save Zegis/797e48116dfdc520c990a86cfb0f8712 to your computer and use it in GitHub Desktop.
Dynamic orderBy
using System;
using System.Collections.Generic;
using System.Linq;
namespace DelegateTest
{
class Pet
{
public string Name { get; set; }
public int Age { get; set; }
}
enum Key
{
Name,
Age
}
class Program
{
public static void Main()
{
Key givenkey = Key.Age;
Pet[] pets = { new Pet { Name="Barley", Age=8 },
new Pet { Name="Boots", Age=4 },
new Pet { Name="Whiskers", Age=1 } };
Console.Write("A sortuje po wieku, wszystko inne po Nazwie\n");
ConsoleKeyInfo input = Console.ReadKey();
Console.WriteLine("");
givenkey = (input.KeyChar == 'A') ? Key.Age : Key.Name;
Func<Pet, Object> orderByFunct = generate(givenkey);
IEnumerable<Pet> query = pets.OrderBy(orderByFunct);
foreach (Pet pet in query)
{
Console.WriteLine("{0} - {1}", pet.Name, pet.Age);
}
Console.ReadKey();
}
public static Func<Pet, object> generate(Key field)
{
Func<Pet, object> a;
if (field == Key.Age)
{
a = (source) => { return source.Age; };
}
else
{
a = (source) => { return source.Name; };
}
return a;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment