I'm pretty new to LINQ and want to make sure I am using it correctly. I've got a dictionary of hostnames as keys and the last time they were contacted as values. I wanted to make a list of all the hosts that had been contacted within a certain amount of time. My first approach was to write a foreach loop, check the value of each pair, and make an array of the names that passed the check. But then I figured there was a more elegant way to do this with LINQ.
const int HOST_POLL_INTERVAL = 60;
const int INTERVAL_EPSILON = 5;
Dictionary<string, DateTime> _hosts = new Dictionary<string, DateTime>();
bool IsHostCurrent(DateTime lastContact)
{
return (DateTime.Now - lastContact).TotalSeconds < HOST_POLL_INTERVAL + INTERVAL_EPSILON;
}
public IEnumerable<string> GetHostList()
{
return _hosts.Where(kvp => IsHostCurrent(kvp.Value)).Select(kvp => kvp.Key);
}
I've got a long way to go in development before I'll be able to put this in a debugger and try it out, but I wanted to make sure I was on the right track. It compiles, but that only gives me so much confidence. Is this the right way to use LINQ for this case?
EDIT: Added "code review" suggestions. Thanks everyone!
-
Yes, but I don't want all the keys, just ones where the corresponding value matches certain criteria.metalhead– metalhead2014年04月16日 23:48:49 +00:00Commented Apr 16, 2014 at 23:48
-
@Jeff, How he can use it?Hamlet Hakobyan– Hamlet Hakobyan2014年04月16日 23:49:26 +00:00Commented Apr 16, 2014 at 23:49
-
Looks reasonably correct to me.Tim Destan– Tim Destan2014年04月16日 23:51:29 +00:00Commented Apr 16, 2014 at 23:51
-
2Yes, this seems to be okay. Plus, I'd advise to return IEnumerable<string> from the GetHostList method instead of an array, let the caller materialize the result when he chooses to.voidengine– voidengine2014年04月16日 23:51:33 +00:00Commented Apr 16, 2014 at 23:51
-
2One other problem, you probably shouldn't call .ToArray at the end, since that forces the enumeration (even though you are returning an IEnumerable).BradleyDotNET– BradleyDotNET2014年04月16日 23:57:21 +00:00Commented Apr 16, 2014 at 23:57
1 Answer 1
From what I'm seeing it looks like correct syntax, and it will give you what you want, however, you might be better off just returning the IEnumerable collection, as you can do more with that later, but that is really just a style issue.
EDIT
I ran this code in a simple console application with some seeded data and it worked great. so to answer your question simply, yes this is the correct syntax in this situation to implement linq expressions.