Search code examples
c#multiple-value

How to remove all except exception in string with multiple value for if-statement


in this multiple value exception for if-statement, I accept the condition if any value from my list is exist in the given string and then I remove this values from string:

using System;
using System.Collections.Generic;
using System.Linq;

namespace _01_WORKDOC
{
    class Program
    {
        static void Main(string[] args)
        {
            string searchin = "You cannot successfully determine beforehand which side of the bread to butter"; 
            var valueList3 = new List<string> { "successfully", "determine", "bread", "the", "to" }; 

            if (valueList3.Any(searchin.Contains)) 
            {
                string exceptions3 = "successfully determine bread the to"; 
                string[] exceptionsList3 = exceptions3.Split(' ');
                string test3 = searchin;
                string[] wordList3 = test3.Split(' ');
                string outtxt = null;
                var text = wordList3.Except(exceptionsList3).ToArray();
                outtxt = String.Join(" ", text);

                Console.WriteLine("Input: " + searchin + "\nOutput: " + outtxt + "\n");              
            }
            Console.Read();
        }
    }
}

My question is how in this code keep exceptions and remove everything else, except this words. So actual result is:

Input: "You cannot successfully determine beforehand which side of the bread to butter"
Output: "You cannot beforehand which side of butter"

but what can I do if with using of this same list var valueList3 = new List<string> { "successfully", "determine", "the", "bread", "to" }; I want get this result.

Input: "You cannot successfully determine beforehand which side of the bread to butter"
Output: "successfully determine the bread to"

Correct to say I want both for same statement:

 Input: "You cannot successfully determine beforehand which side of the bread to butter"
 Output A: "You cannot beforehand which side of butter"
 Output B: "successfully determine the bread to"

And of course I'm not asking for this:

var valueList3 = new List<string> { "You", "cannot", "beforehand", "which", "side", "of", "butter" }; 

but with same list:

  var valueList3 = new List<string> { "successfully", "determine", "the", "bread", "to" };

Solution

  • So this code :

    string text = "You cannot successfully determine beforehand which side of the bread to butter"; 
    var words = new List<string>{ "successfully", "determine", "the", "bread", "to" };
    
    var foundWords = string.Join(" ", words.Where(word => text.Contains(word)));
    
    Console.WriteLine("Input: " + text + "\nOutput: " + foundWords + "\n"); 
    

    Will give this output :

    • Input: You cannot successfully determine beforehand which side of the bread to butter
    • Output: successfully determine the bread to