开发者

A problem with compare item value

I have defined my class:

public class Host 
{
     public string Name;
}

then a strongly-typed dictionary:

Dictio开发者_C百科nary<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 ?


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.


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.


The problem might also be in your string comparison:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜