0

I would like to know how to select only the distinct names from an array. What I did was to read from a text file which contains many irrelevant information. My output results for my current codes is a list of names. I want to select only 1 of each name from the text file.

Following are my codes:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.IO;

namespace Testing
{
class Program
{
    public static void Main(string[] args)
    {
        String[] lines = File.ReadLines("C:\\Users\\Aaron\\Desktop\\hello.txt").ToArray();

        foreach (String r in lines)
        {
            if (r.StartsWith("User Name"))
            {
                String[] token = r.Split(' ');
                Console.WriteLine(token[11]);
            }
        }
    }
}
}
athgap
  • 165
  • 1
  • 6
  • 13
  • check this out [http://stackoverflow.com/questions/9673/remove-duplicates-from-array](http://stackoverflow.com/questions/9673/remove-duplicates-from-array) – Waqas Nov 24 '10 at 06:30

1 Answers1

2

Well, if you're reading them like this you could just add them to a HashSet<string> as you go (assuming .NET 3.5):

HashSet<string> names = new HashSet<string>();
foreach (String r in lines)
{
    if (r.StartsWith("User Name"))
    {
        String[] token = r.Split(' ');
        string name = token[11];
        if (names.Add(name))
        {
            Console.WriteLine(name);
        }
    }
}

Alternatively, think of your code as a LINQ query:

var distinctNames = (from line in lines
                     where line.StartsWith("User Name")
                     select line.Split(' ')[11])
                    .Distinct();
foreach (string name in distinctNames)
{
    Console.WriteLine(name);
}
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194