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 Us开发者_如何学编程ersList, else, I must add it to UsersList.
How can I do that using Linq?
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.
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
精彩评论