Problem with comparison item value

I defined my class:

public class Host 
{
     public string Name;
}

then a strongly typed dictionary:

Dictionary<string, Host> HostsTable;

then I'm trying to compare the value:

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

and the problem is that nothing was found, even I'm sure the item is in the list. What am I doing wrong?

+3
source share
3 answers

Where()returns one more IEnumerable<Host>, so your test for null does not check for the presence of the corresponding element.

I think this is what you are trying to do:

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

Any()returns trueif there are any elements matching the condition.

+5
source

Try the following:

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

The operator Wherefilters the sequence based on the predicate.

Any , .

. linq MSDN.

+1

The problem may also be in string comparison:

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

Source: https://habr.com/ru/post/1736805/


All Articles