To remove empty, whitespace, and duplicate elements from a string array in C#, you can use the following code:

string[] originalArray = {'hello', '  ', 'world', 'world', '', '  ', '  ', 'example'};

string[] newArray = originalArray
    .Where(s => !string.IsNullOrWhiteSpace(s)) // removes empty and whitespace elements
    .Distinct() // removes duplicate elements
    .ToArray(); // convert to array

// newArray will contain {'hello', 'world', 'example'}

Explanation:

  • Where(s => !string.IsNullOrWhiteSpace(s)) uses a lambda expression to filter out any elements that are empty or only contain whitespace.
  • Distinct() removes any duplicate elements from the array.
  • ToArray() converts the result to an array.
C# Remove Empty, Whitespace, and Duplicate Elements from String Array

原文地址: https://www.cveoy.top/t/topic/oO63 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录