开发者

C# selecting distinct names from an array [duplicate]

开发者 https://www.devze.com 2023-01-26 11:23 出处:网络
This question already has answers here: 开发者_StackOverflow中文版How do I remove duplicates from a C# array?
This question already has answers here: 开发者_StackOverflow中文版 How do I remove duplicates from a C# array? (28 answers) Closed 9 years ago.

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);
}
0

精彩评论

暂无评论...
验证码 换一张
取 消