posted 7/3/2011 by Raghav Khunger
Today I was in a need where I need to check in which set of ranges my input number falls. I was having a set of ranges with me like [101,200], [201,300],[301,400]... and I had to check in which of this set my input number falls. I decided to write a blog on the same. Below is the code for it:Code:
using System; using System.Collections.ObjectModel; using System.Linq; namespace MyConsole { class Program { static void Main(string[] args) { var ranges = new Collection<MyRange> { new MyRange {Lower = 101, Upper = 200}, new MyRange {Lower = 201, Upper = 300}, new MyRange {Lower = 301,Upper = 400}, new MyRange {Lower = 401, Upper = 500}, }; const int numberToFind = 250; var myRange = ranges.FirstOrDefault(range => numberToFind >= range.Lower && numberToFind <= range.Upper); Console.WriteLine("Lower:{0}, Upper:{1}", myRange.Lower, myRange.Upper); Console.ReadLine(); } } public class MyRange { public int Lower { get; set; } public int Upper { get; set; } } }
Above we have a set of ranges as mentioned above and my input is 250 in this case and I need to find out in which set this number falls. I decided to go with LINQ in order to do so. As you can see above following is the code used to determine the set:
var myRange = ranges.FirstOrDefault(range => numberToFind >= range.Lower && numberToFind <= range.Upper);
i.e the above code will will traverse the each set one by one and the first record which matches the condition will be our output. Below is the output after running the above code:
Do let me know your feedback, comments.
What kind of email newsletter would you prefer to receive from CodeAsp.Net?18