Where there is a will, there is a way. When you declare a list (like List<Person>, in my example), you will need to add System.Collections.Generic namespace. Now, if you also add System.Linq namespace, you will get a couple more methods to use with your list that you would not get if you just added System.Collections.Generic namespace. These methods will allow you to do more with your list. Hence, to find distinct values for member variables based on my example below, the following statement will suffice.
distinctAges = people.Select(c => c.Age).Distinct().ToList();
That simple. The Select is not available for use until you add System.Linq namespace. The revised code will then be as follows: public partial class Default1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
List<Person> people = new List<Person>();
people.Add(new Person() { FirstName = "Gill", LastName = "Julian", Age = 20 });
people.Add(new Person() { FirstName = "Hill", LastName = "Andrew", Age = 19 });
people.Add(new Person() { FirstName = "Hart", LastName = "Brett", Age = 24 });
people.Add(new Person() { FirstName = "Dwight", LastName = "Jane", Age = 20 });
people.Add(new Person() { FirstName = "Gary", LastName = "Gray", Age = 18 });
people.Add(new Person() { FirstName = "Prim", LastName = "Anne", Age = 19 });
List<int> distinctAges = new List<int>();
////get a list of distinct ages from 'people' list: looping
//foreach(Person person in people)
// if(!distinctAges.Contains(person.Age))
// distinctAges.Add(person.Age);
//get a list of distinct ages from 'people' list: delegate
distinctAges = people.Select(c => c.Age).Distinct().ToList();
}
public class Person
{
public string FirstName;
public string LastName;
public int Age;
}
}
Thanks everyone