2010-11-24 3 views
0

Je voudrais savoir comment ne sélectionner que les noms distincts d'un tableau. Ce que j'ai fait était de lire à partir d'un fichier texte qui contient de nombreuses informations non pertinentes. Mes résultats de sortie pour mes codes actuels sont une liste de noms. Je veux sélectionner seulement 1 de chaque nom du fichier texte.C# sélection de noms distincts d'un tableau

Voici mes 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]); 
      } 
     } 
    } 
} 
} 
+0

check this out [http://stackoverflow.com/questions/9673/re move-duplicates-from-array] (http://stackoverflow.com/questions/9673/remove-duplicates-from-array) – Waqas

Répondre

2

Eh bien, si vous les lire comme ça vous pouvez simplement les ajouter à une HashSet<string> que vous allez (en supposant .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); 
     } 
    } 
} 

Sinon, pensez à votre code comme une requête LINQ:

var distinctNames = (from line in lines 
        where line.StartsWith("User Name") 
        select line.Split(' ')[11]) 
        .Distinct(); 
foreach (string name in distinctNames) 
{ 
    Console.WriteLine(name); 
} 
Questions connexes