An example of a (LINQ) approach to solve recurring problems
Introduction
Most of the time,we think about LINQ in terms of querying the data model .
However ,it can give a set of alternative solutions to problems that we just drill in in a very primitive and basic way.That is because it is used to perform operations on generics of any data type.
Problem
One task I handled lately was to find the gap in a series of numbers.Let us discuss the first solution that comes into one's mind when he approach the task at the first stage.
First Solution
To be able to follow the discussion.create a .NET console application and copy the below code inside program.cs class file
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
namespace NumberSeriesGapFinder
{
class Program
{
static void Main(string[] args)
{
string inputNumbers;
Console.WriteLine("Enter a set of numbers comma seperated,make sure there is no gap in the set");
Console.WriteLine("for example:1,2,4,5 has a gap while 6,7,8,9 has no gap");
inputNumbers = Console.ReadLine();
try
{
CheckGap(inputNumbers);
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
Console.ReadLine();
}
static void CheckGap(string inputNumbers)
{
bool GapExist = false;
List<string> SetElements;
SetElements = inputNumbers.Split(",".ToCharArray()[0]).ToList();
for (int i=0;i<SetElements.Count-1;i++)//here we are execluding the last element
//if the series ends at 8 it wil not contain 9
{
if(!SetElements.Contains((int.Parse(SetElements.ElementAt(i))+1).ToString()))
{
GapExist = true;
break;
}
}
if(GapExist)
{
Console.WriteLine("Gap Exist in the series,please try again");
inputNumbers = Console.ReadLine();
CheckGap(inputNumbers);
}
else
{
Console.WriteLine("The series entered has no gaps");
}
}
}
}
//####################
Comments
Post a Comment