Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare values in 2 lists

Tags:

c#

linq

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

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

UsersList = new List<string>();

I need to compare the values from Users with TestList.Name. If the value in TestList.Name is present in Users, I must must not add it to UsersList, else, I must add it to UsersList.

How can I do that using Linq?

like image 603
learning Avatar asked Dec 28 '22 23:12

learning


1 Answers

It looks to me like you want:

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

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

That's assuming you don't have anything in usersList to start with. If usersList already exists and contains some values, you could use:

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

Note that this won't take account of the existing items in usersList, so you may end up with duplicates.

like image 171
Jon Skeet Avatar answered Dec 30 '22 12:12

Jon Skeet