Skip to content

Instantly share code, notes, and snippets.

@dandohotaru
Last active December 12, 2017 23:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dandohotaru/3c2a2b4eb1a07c43cb66c7044ed3f7ce to your computer and use it in GitHub Desktop.
Save dandohotaru/3c2a2b4eb1a07c43cb66c7044ed3f7ce to your computer and use it in GitHub Desktop.
void Main()
{
var listOfPersons = new List<Person>
{
new Person(){Id = 1, FirstName = "John", LastName = "Doe", CountryName = "UK", City = "London" },
new Person(){Id = 2, FirstName = "Jane", LastName = "Doe", CountryName = "UK", City = "Manchester" },
new Person(){Id = 3, FirstName = "Jim", LastName = "Boe", CountryName = "UK", City = "Brighton" },
new Person(){Id = 4, FirstName = "Jack", LastName = "Dob", CountryName = "UK", City = "London" },
};
listOfPersons
.Query(p => p.Id)
.Dump("ids");
listOfPersons
.Query(p => p.FirstName)
.Dump("names");
listOfPersons
.Query("cityName")
.Dump("cities");
}
public class Person
{
public int Id { get; set; }
public string City { get; set; }
public string CountryName { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
public static class Extensions
{
public static List<T> Query<T>(this IEnumerable<Person> instance, Func<Person, T> selector)
{
return instance
.Select(selector)
.Distinct()
.OrderBy(x => x)
.ToList();
}
public static List<string> Query(this IEnumerable<Person> instance, string property)
{
switch (property)
{
case "ids": return instance.Query(p => p.Id.ToString());
case "firstName": return instance.Query(p => p.FirstName);
case "lastName": return instance.Query(p => p.LastName);
case "countryName": return instance.Query(p => p.CountryName);
case "cityName": return instance.Query(p => p.City);
default: throw new Exception($"{property} is not supported");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment