简体   繁体   English

C#不同的逗号分隔值不起作用

[英]C# Distinct Comma-separated values not working

I am trying to remove duplicate values from a comma-separated string, and am having inconsistent results. 我试图从逗号分隔的字符串中删除重复的值,并且结果不一致。 For example, 例如,

If I pass: 如果我通过:

STA27,STA27,STA27B,STA27A,STA27B, STA27,STA27,STA27B,STA27A,STA27B,

I get: 我得到:

STA27,STA27,STA27B,STA27A, STA27,STA27,STA27B,STA27A,

Or, if I pass: 或者,如果我通过:

STA24,STA24,STA24,STA24, STA24,STA24,STA24,STA24,

I get: 我得到:

STA24,STA24, STA24,STA24,

I've tried several ways to get rid of the comma on the end, but nothing seems to work. 我尝试了几种方法来消除逗号,但似乎没有任何效果。 I don't understand why Distinct isn't working either. 我不明白为什么Distinct也不起作用。 I thought it had something to do with the way the string is terminated, but in the first example I'm getting duplicates of the first two entries, so it doesn't seem to be a position issue. 我认为这与字符串终止的方式有关,但是在第一个示例中,我得到了前两个条目的重复,因此这似乎不是位置问题。

Any thoughts? 有什么想法吗?

 public string FindDistinctBeats(String Beats)
    // Accept comma-separated string, return distinct values
    {
        string result = string.Empty;

        try
        {
            result = string.Join(",", Beats.Split(',').Distinct().ToArray());
            result = result.TrimEnd(',');

            if (String.IsNullOrEmpty(result))
            {
                return result;
            }
            else
            {
                return result.TrimEnd(result[result.Length - 1]);
            }

        }
        catch (Exception e)
        {
            return e.ToString();
        }
    }

A simple test shows the expected results: 一个简单的测试显示了预期的结果:

public class Distinct
{
    private string input = "STA27,STA27,STA27B,STA27A,STA27B,";

    [Test]
    public void DistinctTest()
    {
        var distincts = input.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Distinct();
        foreach(var entry in distincts)
        {
            Console.WriteLine(entry);
        }
    }
}

Output 输出量

STA27
STA27B
STA27A

You were missing the StringSplitOptions.RemoveEmptyEntries options, as already mentioned. 如前所述,您缺少StringSplitOptions.RemoveEmptyEntries选项。 Also, consider cleaning up your string before doing the split, something like this: 另外,考虑在拆分之前清理字符串,如下所示:

// test string with some whitespace and a control char in the end of the string
string beats = "STA27,STA27,STA27B,STA27A,STA27B,   " + '\u0002'; 

beats = string.Join(string.Empty, beats.ToCharArray().Where(x => !Char.IsControl(x) && !Char.IsWhiteSpace(x)));

List<string> distinctBeats = beats.Split(",", StringSplitOptions.RemoveEmptyEntries)
                                  .Distinct()
                                  .ToList();

And in case you need a case-insensitive distinct, you can use a StringComparer (in this case, StringComparer.InvariantCultureIgnoreCase ): 并且如果您需要区分大小写的区分符,则可以使用StringComparer(在这种情况下为StringComparer.InvariantCultureIgnoreCase ):

List<string> distinctBeats = beats.Split(",", StringSplitOptions.RemoveEmptyEntries)
                                  .Distinct(StringComparer.InvariantCultureIgnoreCase)
                                  .ToList();

Many answers have the proper guidance, but I want to point out that the original code had 2 issues. 许多答案都有正确的指导,但我想指出,原始代码有2个问题。 However, the code as written above run with the input provided does not return the output you specified. 但是,上面提供的输入运行的上述代码不会返回您指定的输出。 I created a fiddler below to show that. 我在下面创建了一个提琴手来说明这一点。

One is the return result.TrimEnd(result[result.Length - 1]); 一个是return result.TrimEnd(result[result.Length - 1]); which knocks off that last character of the result. 从而消除了结果的最后一个字符。 With that if statement removed, the code works fine. 删除了if语句后,代码可以正常工作。

The other is the trailing comma. 另一个是结尾逗号。 While you are handling with removing the trailing comma explicitly, you can also use StringSplitOptions.RemoveEmptyEntries . 在处理显式删除尾随逗号的过程中,还可以使用StringSplitOptions.RemoveEmptyEntries The trailing space causes string.Empty to be the last result in your split. 尾随空格导致string.Empty是拆分中的最后一个结果。

Here's an example program, and here is a link to a fiddler to run it: 这是一个示例程序, 这是一个运行提琴手的链接

using System;
using System.Linq;

public class Program
{
    public static void Main()
    {
        Console.WriteLine("Original:");
        Console.WriteLine(OriginalFindDistinctBeats("STA24,STA24,STA24,STA24,"));
        Console.WriteLine(OriginalFindDistinctBeats("STA27,STA27,STA27B,STA27A,STA27B,"));

        Console.WriteLine();

        Console.WriteLine("New working (removed that weird if statement):");
        Console.WriteLine(NewFindDistinctBeats("STA24,STA24,STA24,STA24,"));
        Console.WriteLine(NewFindDistinctBeats("STA27,STA27,STA27B,STA27A,STA27B,"));

        Console.WriteLine();

        Console.WriteLine("New working with remove empty:");
        Console.WriteLine(NewWithRemoveEmptyFindDistinctBeats("STA24,STA24,STA24,STA24,"));
        Console.WriteLine(NewWithRemoveEmptyFindDistinctBeats("STA27,STA27,STA27B,STA27A,STA27B,"));
    }

    public static string OriginalFindDistinctBeats(String Beats)
    // Accept comma-separated string, return distinct values
    {
        string result = string.Empty;

        try
        {
            result = string.Join(",", Beats.Split(',').Distinct().ToArray());
            result = result.TrimEnd(',');

            if (String.IsNullOrEmpty(result))
            {
                return result;
            }
            else
            {
                return result.TrimEnd(result[result.Length - 1]);
            }

        }
        catch (Exception e)
        {
            return e.ToString();
        }
    }

    public static string NewFindDistinctBeats(String Beats)
    // Accept comma-separated string, return distinct values
    {
        string result = string.Empty;

        try
        {
            result = string.Join(",", Beats.Split(',').Distinct().ToArray());
            result = result.TrimEnd(',');

            return result;
        }
        catch (Exception e)
        {
            return e.ToString();
        }
    }

    public static string NewWithRemoveEmptyFindDistinctBeats(String Beats)
    // Accept comma-separated string, return distinct values
    {
        string result = string.Empty;

        try
        {
            result = string.Join(",", Beats.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Distinct().ToArray());

            return result;
        }
        catch (Exception e)
        {
            return e.ToString();
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM