Let’s see how one would approach this problem without programming and you would able to solve it by applying similar process in pseudocode:
(1) Examine each character in aaaa
(2) If the character exists in dddd
, keep it as it is
(3) Otherwise, output -
instead
We can solve (1) by iterating over aaaa
by using for
, foreach
or while
loop, which was shown in @Arphile’s and your solution.
On the other hand, we may solve (2) by using similar approach in (1) as well since we need to iterate over dddd
to find whether there’s a match. Fortunately we can save that effort by using Contains
as shown in @Arphile’s answer as well.
Lastly, the conditional can be achieved using if-else
or an elvis / conditional operator ?:
.
Combining all of these along with LINQ, we will have something like this:
char[] charList = new [] { 'H','e','l','l','o','g','o','o','d','m','o','r','n','i','n','g' };
char[] allowedChars = new [] { 'e','l','g','o','d' };
IEnumerable<char> filteredChars = charList.Select(c => allowedChars.Contains(c) ? c : '-');
// Output : -,e,l,l,o,g,o,o,d,-,o,-,-,-,-,g
Console.WriteLine(string.Join(",", filteredChars));
Side note: You may append ToArray
if would like to keep the filtered characters in an array instead.
2
solved How to make a foreach loop with true and false condition? [closed]