C# selecting distinct names from an array [duplicate]
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]);
}
}
}
}
}
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);
}
精彩评论