There is a class DB

class DB { private List<string> newList; public string Naimenovanie { get; set; } public string Url { get; set; } } 

Later I use List<DB> listDB = new List<DB>(); to insert instances of the class DB in the loop.

There is also a separate list. List<string> urls = new List<string>();

How to compare the elements of the listDB.Url and urls and remove from the listDB those url elements which are equal to the url of the urls list

I see it as creating a double loop and comparing elements. I think there is a simple solution through linq .

    2 answers 2

    To avoid double-looping, I would add the url to be removed in the HashSet :

     var urlSet = new HashSet<string>(urls); 

    After that, you simply

     listDB.RemoveAll(db => urlSet.Contains(db.Url)); 

    This is not entirely LINQ, but I think the fastest way is if you have large enough lists.

    If both lists are small, probably it would rather do without an auxiliary set:

     listDB.RemoveAll(db => urls.Contains(db.Url)); 

    At the same time, urls.Contains runs through the list in the list of urls (and here urlSet.Contains answers for O (1)).

       List<DB> listDB = new List<DB>() { new DB { Url = "test1" }, new DB { Url = "test2" }, new DB { Url = "test3" }, new DB { Url = "test4" }, }; List<string> urls = new List<string>() { "test2", "test5" }; listDB.RemoveAll(x => urls.Exists(y => y == x.Url)); 

      the 2nd item is removed from listDB