I wish to search to see if a string called tempName is already contained in a List of user objects. These user objects of type userClass contain a string data method Name whose value i’d like to check against tempName.
How is this done in LINQ?
thanks
Using traditional for loops i can do it like this:
bool already = false;
for (int i = 0; i < userList.Count; i++)
{
if (Name == userList[i].name)
already = true;
}
You can use
Enumerable.Any, which uses an expression lambda (the bit withuser =>) to specify the function used to test each user, and returns a boolean value:This has the (performance) advantage that it doesn’t enumerate over all elements; it bails out once it finds the first element that satisfies the condition you specify.