learning
learning

Reputation: 11725

How to compare values in 2 lists

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?

Upvotes: 4

Views: 2205

Answers (2)

Xai
Xai

Reputation: 38

Do a loop on you list - for example :

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

..that's how I interpreted you question

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1499810

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.

Upvotes: 10

Related Questions