0

Say, I have a Person object list called people:

public class Person
{
    public int age;
    public string name;

    public Person(int age, string name)
    {
        this.age = age;
        this.name = name;
    }
}

List<Person> people = new List<Person>();

The list is populated with a large amount of people data. How do I get a list of all the names used in the list, but only one occurrence for each name? For example, if in the people List there are 1000 people with the firstname 'Bob' and 200000 with the firstname 'Alice', my list should contain only one entry for 'Bob' and one entry for 'Alice'.

jason
  • 236,483
  • 35
  • 423
  • 525
FunLovinCoder
  • 7,597
  • 11
  • 46
  • 57
  • If this list of people is populated from a database, consider using the database to give you a list of distinct names if that's all you need in your application. – Bernard Feb 08 '12 at 19:41

2 Answers2

6
var names = people.Select(p => p.name).Distinct();
jason
  • 236,483
  • 35
  • 423
  • 525
6

If you're able to use LINQ, it's as easy as:

var distinctNames = people.Select(p => p.name).Distinct();

If not, it's a little bit more complicated:

var distinctNames = new List<string>();

foreach(var person in people)
    if(!distinctNames.Contains(person.Name)) distinctNames.Add(person.Name);

Or, if you're working with large data sets and need something more efficient (at the cost of space):

var distinctNames = new Dictionary<string, string>();

foreach(var person in people)
{
    if(!distinctNames.ContainsKey(person.Name))
    {
        distinctNames.Add(person.Name, person.Name);
    }
}
Justin Niessner
  • 242,243
  • 40
  • 408
  • 536