views:

30

answers:

3

Hi, I have defined my class:

public class Host 
{
     public string Name;
}

then a strongly-typed dictionary:

Dictionary<string, Host> HostsTable;

then I try to compare a value:

 if (HostsTable.Values.Where(s => s.Name == "myhostname") != null) { doSomething }

and the problem is, nothing is found, even I'm sure the item is on the list. What I'm doing wrong ?

+5  A: 

Where() returns another IEnumerable<Host>, so your test for null is not checking that there is a matching item.

I think this is what you are trying to do:

if(HostsTable.Values.Any(s => s.Name == "myhostname")) { doSomething }

Any() returns true if there are any items that match the condition.

GraemeF
+1  A: 

Try this:

 if (HostsTable.Values.Any(s => s.Name == "myhostname")) { doSomething }

The Where operator filters a sequence based on a predicate.

The Any operator determines whether any element of a sequence satisfies a condition.

See the standard linq operators document on MSDN.

Oded
+1  A: 

The problem might also be in your string comparison:

if(HostsTable.Values.Any(s => s.Name.Equals("myhostname", StringComparison.OrdinalIgnoreCase))) { doSomething }
Thomas