A nice little suprise this morning! A quick hit on it - .Contains() returns a bool value and expects you to pass in an object that is in your list whereas .Exists expects a predicate (but still returns a boolean). Let's dive right into this because its easier to show than blab/explain. Make a new list, shove it into view state. Feel free to add this where ever you like, just as long as it is not in pageload, make it a button event.
List<string> Ids = new List<string>();
Ids.Add("007");
Ids.Add("008");
Ids.Add("009");
ViewState.Add("Agents", Ids);
Drop a second button out there and add the following code...
List<string> SavedAgents = ViewState["Agents"] as List<string>;
string FoundAgent = "008";
bool ContainsAgent = SavedAgents.Contains(FoundAgent);
bool IsSavedAgent = SavedAgents.Exists(delegate(string agent)
{
return agent == FoundAgent;
});
This works, both values are true. "So what's the difference?" -- Create yourself the following object...
[Serializable()]
public class Agent
{
public string AgentId { get; set; }
public string AgentName { get; set; }
public string CurrentLocation { get; set; }
public Agent(string agentId, string agentName, string currentLocation)
{
this.AgentId = agentId;
this.AgentName = agentName;
this.CurrentLocation = currentLocation;
}
}
and switch out the code just a touch that loads up the viewstate...
List<Agent> agentList = new List<Agent>();
agentList.Add(new Agent("007", "James Bond", "Las Vegas"));
agentList.Add(new Agent("008", "Unknown", "Unknown"));
agentList.Add(new Agent("009", "David Brabham", "UK"));
ViewState.Add("Agents", agentList);
and the check behind button 2 like so...
List<Agent> SavedAgents = ViewState["Agents"] as List<Agent>;
Agent foundAgent = new Agent("008", "Unknown", "Unknown");
bool ContainsAgent = SavedAgents.Contains(foundAgent);
bool IsSavedAgent = SavedAgents.Exists(delegate(Agent agent)
{
return agent.AgentId == foundAgent.AgentId;
});
This might surprise you, but ContainsAgent will be false. If you do "return agent == foundAgent" for the .Exists, it will also be false. I'm -guessing- it's using reflection. Because of this, I insist using .Exists instead, since you can test properties directly. Even more curiously, using the various .Equals yeilds false, such as :
bool IsEqual = Equal(SavedAgents[1], foundAgent); ...or
bool IsEqual = SavedAgents[1].Equals(foundAgent); ...or even
bool IsEqual = foundAgent.Equals(SavedAgents[1]);