The most efficient way to compare two lists and delete them

I want to compare two lists and get valid words in a new list.

var words = new List<string>();
var badWords = new List<string>();

//this is just an example list. actual list does contain 700 records
words.Add("Apple");
words.Add("Moron");
words.Add("Seafood");
words.Add("Cars");
words.Add("Chicken");
words.Add("Twat");
words.Add("Watch");
words.Add("Android");
words.Add("c-sharp");
words.Add("Fool");

badWords.Add("Idiot");
badWords.Add("Retarded");
badWords.Add("Twat");
badWords.Add("Fool");
badWords.Add("Moron");

I am looking for the most effective way to compare lists and put all the “good” words in a new list. The resulting list should not contain Moron, Tweet, and Fool.

var finalList = new List<string>();

Or is there no need to create a new list? I am glad to hear your ideas!

Thank you in advance

+4
source share
5 answers

Use Enumerable Except Save in NamespaceSystem.Linq

finalList = words.Except(badWords).ToList();

, , Except Set,

+8

Enumerable.Except:

List<string> cleanList = words.Except(badWords).ToList();

, Except , .

, , "" . , HashSet<string> :

var badWords = new HashSet<string>(StringComparer.InvariantCultureIgnoreCase){ "Idiot", "Retarded", "Twat", "Fool", "Moron" };

string word = "idiot";
if (!badWords.Contains(word))
    words.Add(word);
+7

contains

words.Where(g=>!badWords.Contains(g)).ToList()
+3

,

words.RemoveAll(x => badWords.Contains(x));
+1

https://msdn.microsoft.com/library/bb908822(v=vs.90).aspx

var words = new List<string>();
var badWords = new List<string>();

//this is just an example list. actual list does contain 700 records
words.Add("Apple");
words.Add("Moron");
words.Add("Seafood");
words.Add("Cars");
words.Add("Chicken");
words.Add("Twat");
words.Add("Watch");
words.Add("Android");
words.Add("c-sharp");
words.Add("Fool");

badWords.Add("Idiot");
badWords.Add("Retarded");
badWords.Add("Twat");
badWords.Add("Fool");
badWords.Add("Moron");

var result = words.Except(badWords).ToList();

: .

+1

Source: https://habr.com/ru/post/1627754/


All Articles