2010-11-24 53 views
0

我想知道如何從數組中選擇不同的名稱。 我所做的是從包含許多不相關信息的文本文件中讀取數據。 我的當前代碼的輸出結果是一個名稱列表。我想從文本文件中僅選擇每個名稱中的一個。C#從數組中選擇不同的名稱

以下是我的代碼:

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

檢查了這一點[http://stackoverflow.com/questions/9673/re移動-重複-從陣列(http://stackoverflow.com/questions/9673/remove-duplicates-from-array) – Waqas 2010-11-24 06:30:46

回答

2

好吧,如果你正在讀他們這樣你可以只將它們添加到HashSet<string>你去(假設.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); 
     } 
    } 
} 

或者,想你的代碼作爲一個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); 
} 
相關問題