0

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!

asked Apr 16, 2014 at 23:46
10
  • Yes, but I don't want all the keys, just ones where the corresponding value matches certain criteria. Commented Apr 16, 2014 at 23:48
  • @Jeff, How he can use it? Commented Apr 16, 2014 at 23:49
  • Looks reasonably correct to me. Commented Apr 16, 2014 at 23:51
  • 2
    Yes, 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. Commented Apr 16, 2014 at 23:51
  • 2
    One other problem, you probably shouldn't call .ToArray at the end, since that forces the enumeration (even though you are returning an IEnumerable). Commented Apr 16, 2014 at 23:57

1 Answer 1

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.

answered Apr 17, 2014 at 0:04
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.