Как удалить все, кроме исключения, в строке с несколькими значениями для оператора if

в этом исключении с несколькими значениями для оператора if я принимаю условие, если какое-либо значение из моего списка существует в данной строке, а затем я удаляю эти значения из строки:

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();
        }
    }
}

Мой вопрос в том, как в этом коде сохранить исключения и удалить все остальное, кроме этих слов. Итак, фактический результат:

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

но что делать, если с помощью этого же списка var valueList3 = new List<string> { "successfully", "determine", "the", "bread", "to" }; я хочу получить вот такой результат.

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

Правильно сказать, что я хочу оба для одного и того же утверждения:

 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"

И, конечно, я не прошу об этом:

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

но с тем же списком:

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

person Community    schedule 09.09.2016    source источник
comment
Это запутанный вопрос. Каковы ваши ожидаемые результаты?   -  person Kinetic    schedule 09.09.2016
comment
@Kinetic привет, отредактировано, все показано выше   -  person    schedule 09.09.2016
comment
Я написал свой комментарий после того, как вы закончили редактирование.   -  person Kinetic    schedule 09.09.2016
comment
Итак, в основном у вас есть текст в строке и набор слов в массиве. На выходе должны быть слова из массива, которые есть в тексте?   -  person Kinetic    schedule 09.09.2016
comment
@Кинетический вывод с заданным кодом также Input: "You cannot successfully determine beforehand which side of the bread to butter" Output: "You cannot beforehand which side of butter" показывает ввод. Желаемый выход - если я могу оставить только исключения, не меняя список в противоположных словах   -  person    schedule 09.09.2016
comment
Вы получите этот вывод, используя какие слова в valueList3?   -  person Kinetic    schedule 09.09.2016


Ответы (1)


Итак, этот код:

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"); 

Дает этот вывод:

  • Вход: вы не можете заранее определить, какую сторону хлеба смазывать маслом.
  • Вывод: успешно определить хлеб для
person Kinetic    schedule 09.09.2016
comment
именно то, что мне нужно, очень полезно - person ; 09.09.2016