-1

I've tried several methods to remove duplicate elements from an array of strings, but none of them do what I want. Here are 2 strings:

CNTY/013121/261538/Y/Y/Y/Y/Y/Y/C/NOSPACE//

CNTY/013121/261538/Y/Y/Y/Y/Y/Y/C/NO SPACE//

I want just one of these to be retained as they are copied from array a to array b. It doesn't matter which one.

I have tried IEnumerable, HashSet, and Distinct. Each of them returns both strings. (An error of mine duplicated the second string. Sorry. To be clear, I want the compare to ignore whitespace.)

IEnumerable<string> b = a.AsQueryable().Distinct(StringComparer.InvariantCulture);

HashSet<string> set = new HashSet<string>(a);
string[] b = new string[set.Count];
set.CopyTo(b);

string[] b = a.Distinct().ToArray();
Buck
  • 37
  • 6
  • Is it intentional that there is a space missing in the first element in `"NOSPACE"`? – sticky bit Apr 20 '19 at 15:15
  • Since the main complication in this is the whitespace, there are other similar question on so... https://stackoverflow.com/q/4718965/8723329 https://stackoverflow.com/q/6859255/8723329 – Jonathon K Apr 20 '19 at 15:33
  • With string compare, I'll need to compare every string in the array against every other string. I was hoping that IENumerable, or HashSet, or Distinct had an option to ignore whitespace. Thanks for help. – Buck Apr 20 '19 at 16:41

1 Answers1

1

The first element isnt the same as the others, so distinct will not gonna work for this, you must replace the space char.

string[] a = { "CNTY/013121/261538/Y/Y/Y/Y/Y/Y/C/NOSPACE//", "CNTY/013121/261538/Y/Y/Y/Y/Y/Y/C/NO SPACE//", "CNTY/013121/261538/Y/Y/Y/Y/Y/Y/C/NO SPACE//" };
string[] b = a.Select(p => p.Replace(" ", "")).Distinct().ToArray(); //Replace 

output:

"CNTY/013121/261538/Y/Y/Y/Y/Y/Y/C/NOSPACE//",
Paulo Campez
  • 702
  • 1
  • 8
  • 24