I have a Person class that looks like the following:
public class Person
{
public Person() { }
public Person(string name, int age, GenderType gender, string country) { Name = name; Age = age; Gender = gender; Country = country; }
public string Name { get; set; }
public int Age { get; set; }
public GenderType Gender { get; set; } // GenderType = M/F
public string Country { get; set; }
}
I would like to divide this list into two lists first, based on Gender. Then I want to further divide each list into sub-lists, based on Country. So if I have n-number of distinct countries in the original list, I'd get anywhere from n to 2n number of lists at the end. The following example will further illustrate the idea:
Say my original list is like this:
Sam, 23, M, USA
Jon, 13, M, USA
Jen, 26, F, USA
Thilini, 25, F, Sri Lanka
Anna, 23, F, UK
Chelsea, 35, F, UK
Saman, 43, M, Sri Lanka
Dan, 27, M, UK
First division:
Male lists:
Sam, 23, M, USA
Jon, 13, M, USA
Saman, 43, M, Sri Lanka
Dan, 27, M, UK
------------------
Female lists:
Jen, 26, F, USA
Thilini, 25, F, Sri Lanka
Anna, 23, F, UK
Chelsea, 35, F, UK
Then further subdivided lists:
Male sub-list 1:
Sam, 23, M, USA
Jon, 13, M, USA
Male sub-list 2:
Saman, 43, M, Sri Lanka
Male sub-list 3:
Dan, 27, M, UK
------------------
Female sub-list 1:
Jen, 26, F, USA
Female sub-list 2:
Thilini, 25, F, Sri Lanka
Female sub-list 3:
Anna, 23, F, UK
Chelsea, 35, F, UK
I would easily be able to do this using foreach loops and going through each item with perhaps the use of a Results class. But I would like to learn how I could do this using Linq GroupBy() and maybe Distinct()?
I used GroupBy() to divide this into two lists based on Gender as follows.
static void Main(string[] args)
{
List<Person> people = new List<Person>()
{
new Person("Sam", 23, GenderType.M, "USA"),
new Person("Jon", 13, GenderType.M, "USA"),
new Person("Jen", 26, GenderType.F, "USA"),
new Person("Thilini", 25, GenderType.F, "Sri Lanka"),
new Person("Anna", 23, GenderType.F, "UK"),
new Person("Chelsea", 35, GenderType.F, "UK"),
new Person("Saman", 43, GenderType.M, "Sri Lanka"),
new Person("Dan", 27, GenderType.M, "UK")
};
var maleList = people.GroupBy(x => x.Gender).Where(y => y.Key == GenderType.M);
var femaleList = people.GroupBy(x => x.Gender).Where(y => y.Key == GenderType.F);
Console.ReadLine();
}
I don't understand how I would sub-divide each list now into many again based on Country.