Most efficient way to compare two lists and delete the same

前端 未结 5 1395
执笔经年
执笔经年 2021-01-19 16:57

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

var words = new List();
var badWords = new List();

//this i         


        
5条回答
  •  不思量自难忘°
    2021-01-19 17:21

    Use Enumerable.Except:

    List 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 with a case-insensitive comparer:

    var badWords = new HashSet(StringComparer.InvariantCultureIgnoreCase){ "Idiot", "Retarded", "Twat", "Fool", "Moron" };
    
    string word = "idiot";
    if (!badWords.Contains(word))
        words.Add(word);
    

提交回复
热议问题