C# TextLogger开发问题:移除两数组中共有的字符
Hey Daniel, let's work through this problem to get your TextLogger functionality sorted out! The goal is to remove any characters that exist in both of your arrays, then combine the remaining elements into the expected output: a, b, d, h, y, f. Here's how to implement this, whether you want to use LINQ (for simplicity) or manual loops (if you need more control):
Option 1: Using LINQ (Clean & Concise)
LINQ makes this task straightforward with built-in methods for finding intersections and filtering elements. Let's assume your existing code has two character arrays like this:
char[] array1 = { 'a', 'b', 'c', 'd', 'h' }; char[] array2 = { 'c', 'y', 'f' };
Follow these steps:
- Find common characters between the two arrays:
// Get all characters present in both arrays var commonChars = array1.Intersect(array2).ToArray(); - Filter out common characters from each array:
// Keep only characters not in the common set var filteredArray1 = array1.Where(c => !commonChars.Contains(c)).ToArray(); var filteredArray2 = array2.Where(c => !commonChars.Contains(c)).ToArray(); - Combine and output the result:
// Merge the filtered arrays and format as comma-separated text var finalResult = filteredArray1.Concat(filteredArray2).ToArray(); Console.WriteLine(string.Join(", ", finalResult));
Running this will give you exactly the output you want: a, b, d, h, y, f.
Option 2: Manual Implementation (No LINQ)
If you prefer to avoid LINQ (e.g., for performance optimization or project constraints), you can use hash sets and loops to achieve the same result:
char[] array1 = { 'a', 'b', 'c', 'd', 'h' }; char[] array2 = { 'c', 'y', 'f' }; // Step 1: Find common characters using a HashSet for fast lookups HashSet<char> array1Set = new HashSet<char>(array1); HashSet<char> commonChars = new HashSet<char>(); foreach (char c in array2) { if (array1Set.Contains(c)) { commonChars.Add(c); } } // Step 2: Filter each array List<char> filtered1 = new List<char>(); foreach (char c in array1) { if (!commonChars.Contains(c)) { filtered1.Add(c); } } List<char> filtered2 = new List<char>(); foreach (char c in array2) { if (!commonChars.Contains(c)) { filtered2.Add(c); } } // Step 3: Combine and output var finalResult = filtered1.Concat(filtered2).ToArray(); Console.WriteLine(string.Join(", ", finalResult));
Notes for Your Existing Code
- If your arrays are derived from strings (e.g., user input or log lines), you can convert them to char arrays like this first:
string input1 = "a,b,c,d,h"; string input2 = "c,y,f"; char[] array1 = input1.Split(',').Select(s => s.Trim()[0]).ToArray(); char[] array2 = input2.Split(',').Select(s => s.Trim()[0]).ToArray(); - This solution handles duplicate characters in either array too—for example, if
array1had two'c's, both would be removed.
内容的提问来源于stack exchange,提问作者Daniel

