Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Most efficient way to compare two lists and delete the same

I want to compare two lists and get the valid words into 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 most efficient way to compare the lists and put all the 'good' words into a new list. The finalList shouldn't contain "Moron", "Twat" and "Fool".

var finalList = new List<string>();

Or is it unnecessary to create a new List? I am happy to hear your ideas!

Thank you in advance

like image 874
deadpool_Y7 Avatar asked Nov 30 '22 23:11

deadpool_Y7


1 Answers

Use EnumerableExcept function storing in System.Linq namespace

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

Most efficient way to save your time and also the fastest way to do it, because Except implementation uses Set, which is fast

like image 170
Konstantin Zadiran Avatar answered Dec 07 '22 01:12

Konstantin Zadiran