metalhead
metalhead

Reputation: 567

Selected array of keys from Dictionary using LINQ

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!

Upvotes: 0

Views: 1243

Answers (1)

tophallen
tophallen

Reputation: 1063

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.

Upvotes: 1

Related Questions