Most efficient way to compare two lists and delete the same

倖福魔咒の 提交于 2019-12-01 22:22:07

问题


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


回答1:


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




回答2:


Use Enumerable.Except:

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

This is efficient because Except uses a set based approach.

An even more efficient approach is to avoid that "bad" words are added to the first list at all. For example by using a HashSet<string> with a case-insensitive comparer:

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

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



回答3:


you can use contains method

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



回答4:


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

Edit: Got in late.




回答5:


If your don't want to create a new List you can remove the bad words from your existing List with RemoveAll()

words.RemoveAll(badWords.Contains);


来源:https://stackoverflow.com/questions/35265926/most-efficient-way-to-compare-two-lists-and-delete-the-same

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!