Click here to Skip to main content
15,879,535 members
Articles / Programming Languages / C#
Tip/Trick

An Example of a (LINQ) Approach to Solve Recurring Problems

Rate me:
Please Sign up or sign in to vote.
3.67/5 (6 votes)
8 Mar 2021CPOL2 min read 7.4K   3   15
How to solve recurring problems using LINQ
In this tip, you will learn how to use LINQ to solve recurring problems. Here, you will see two solutions to find the gap in a series of numbers.

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 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 one approaches 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:

C#
//################
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 separated, 
                               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 excluding the last element 
                                                   //if the series ends at 8 
                                                   //it will 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");
            }
        }
    }
}
//####################

The code above is a very basic solution for the problem, but there are two drawbacks after a deeper look.

  1. It works in a nested loop manner which will keep the memory busy holding loop index and scanning the whole series against each element.
  2. The numbers should be in ascending order since we do not know the element with highest value. This element should be excluded from the check since it is the upper boundary of the series.

Second Solution

Place the following code below method discussed in solution 1:

C#
//##################
static void CheckGap2(string inputNumbers)
        {        
            bool GapExist = false;
            int MaxElement;

            List<string> SetElements,SetElementsMissingSubSequent;
            SetElements = inputNumbers.Split(",".ToCharArray()[0]).ToList();
            MaxElement = (from x in SetElements select int.Parse(x)).Max();

            SetElementsMissingSubSequent = (from x in SetElements.Where
                                           (w=>int.Parse(w)<MaxElement)
                                           join y in SetElements
                                           on (int.Parse(x)+1) equals (int.Parse(y))
                                           into lj 
                                           from ljr in lj.DefaultIfEmpty()
                                                //left join
                                                //is a relational algebra operator that 
                                                //finds out the  elements between 
                                                //two tuples a and b
                                                //which hold the same value for
                                                //join column a as well as the elements in a 
                                                //that have values for the 
                                                //join column that do not exist in b 
                                           where ljr==null
                                           select ljr
                                          ).ToList();
            GapExist = SetElementsMissingSubSequent.Count > 0;

            if (GapExist)
            {
                Console.WriteLine("Gap Exist in the series, please try again");
                inputNumbers = Console.ReadLine();
                CheckGap2(inputNumbers);
            }
            else
            {
                Console.WriteLine("The series entered has no gaps");
            }
        }
//##########

Notice that we have used LINQ to

  1. perform left join operator between the series and itself (you can refresh your information about left using the comments inside the method). Any number where its subsequent does not exist will satisfy the where condition.
  2. Select the element with maximum value of the element. The series does not have to be entered in order this way.

Now call the method from main method and try.

Conclusion

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 a very primitive and basic way. That is because it is used to perform operations on generics of any data type.

History

  • 6th March, 2021: Initial version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



Comments and Discussions

 
PraiseMy vote of 5 Pin
Stylianos Polychroniadis11-Mar-21 5:53
Stylianos Polychroniadis11-Mar-21 5:53 
GeneralMy vote of 5 Pin
Craig Pelkie9-Mar-21 10:08
Craig Pelkie9-Mar-21 10:08 
GeneralRe: My vote of 5 Pin
Basem AlShabani10-Mar-21 2:23
Basem AlShabani10-Mar-21 2:23 
QuestionIs there a one line solution? Pin
George Swan8-Mar-21 21:51
mveGeorge Swan8-Mar-21 21:51 
AnswerRe: Is there a one line solution? Pin
#realJSOP10-Mar-21 1:30
mve#realJSOP10-Mar-21 1:30 
GeneralRe: Is there a one line solution? Pin
George Swan10-Mar-21 5:36
mveGeorge Swan10-Mar-21 5:36 
QuestionHonestly... Pin
#realJSOP8-Mar-21 5:08
mve#realJSOP8-Mar-21 5:08 
AnswerRe: Honestly... Pin
Slacker0078-Mar-21 6:20
professionalSlacker0078-Mar-21 6:20 
GeneralRe: Honestly... Pin
#realJSOP8-Mar-21 8:19
mve#realJSOP8-Mar-21 8:19 
GeneralRe: Honestly... Pin
Slacker0078-Mar-21 8:29
professionalSlacker0078-Mar-21 8:29 
GeneralRe: Honestly... Pin
#realJSOP8-Mar-21 8:56
mve#realJSOP8-Mar-21 8:56 
GeneralRe: Honestly... Pin
Craig Pelkie9-Mar-21 10:06
Craig Pelkie9-Mar-21 10:06 
GeneralRe: Honestly... Pin
#realJSOP10-Mar-21 1:28
mve#realJSOP10-Mar-21 1:28 
The simplest solutions are usually the best, though, especially in production code. That has to be maintained by people that didn't write the original version.

I think banking/corporate finance is one of the few industries I haven't written code for, so I never considered that use case.
".45 ACP - because shooting twice is just silly" - JSOP, 2010
-----
You can never have too much ammo - unless you're swimming, or on fire. - JSOP, 2010
-----
When you pry the gun from my cold dead hands, be careful - the barrel will be very hot. - JSOP, 2013

AnswerRe: Honestly... Pin
Basem AlShabani10-Mar-21 1:28
Basem AlShabani10-Mar-21 1:28 
AnswerRe: Honestly... Pin
Basem AlShabani10-Mar-21 1:31
Basem AlShabani10-Mar-21 1:31 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.