2010-11-24 52 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); 
} 
相关问题