How to compare values ​​in 2 lists

I have a list Users = new List<string>();

I have another list, List<TestList>() ;

 UsersList = new List<string>(); 

I need to compare values ​​from users using TestList.Name. If the value in TestList.Name is present in Users, I must not add it to UsersList, otherwise I must add it to the UsersList list.

How can I do this with Linq?

+4
source share
2 answers

It seems to me that you want:

 List<string> usersList = testList.Select(x = > x.Name) .Except(users) .ToList(); 

In other words, "use all the usernames in testList , except those listed in users , and convert the result to List<string> ".

Suppose you have nothing in usersList to start with. If usersList already exists and contains some values, you can use:

 usersList.AddRange(testList.Select(x = > x.Name).Except(users)); 

Note that this will not account for existing elements in usersList , so you can get duplicates.

+10
source

Do a loop in the list - for example:

 foreach (string s in MyList) { if (!MyList2.Contains(s)) { // Do whatever ; add to the list MyList2.Add(s); } } 

.. that I have interpreted your question

0
source

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


All Articles