【问题标题】:C# selecting distinct names from an array [duplicate]C#从数组中选择不同的名称[重复]
【发布时间】:2011-05-14 22:07:59
【问题描述】:

我想知道如何从数组中只选择不同的名称。 我所做的是从包含许多不相关信息的文本文件中读取。 我当前代码的输出结果是一个名称列表。我只想从文本文件中选择每个名称中的 1 个。

以下是我的代码:

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

【问题讨论】:

标签: c# distinct tokenize diagnostics


【解决方案1】:

好吧,如果您是这样阅读它们的,您可以随时将它们添加到 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);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-23
    • 1970-01-01
    相关资源
    最近更新 更多