All about LINQ operators

A short list of LINQ operators.

Using IN clause

This is similar to database IN keyword;

var myInClause = new string[] {"One", "Two", "Three"};

var results = from x in MyTable
              where myInClause.Contains(x.SomeColumn)
              select x;
// OR
var results = MyTable.Where(x => myInClause.Contains(x.SomeColumn));

Using ALL operator

Working with simple types

//does all numbers are greater than 10
int[] IntArray = { 11, 22, 33, 44, 55 };
var Result = IntArray.All(x => x > 10);
Console.WriteLine("Is All Numbers are greater than 10 : " + Result);

//does all names has characters greater than three
string[] stringArray = { "Khan", "Ali", "Adam", "Eve", "Joe" };
Result = stringArray.All(name => name.Length > 3);
Console.WriteLine("Is All Names are greater than 3 Characters : " + Result);

var letterResult = stringArray.All(name => name.StartsWith("A"));
Console.WriteLine("Is All Names start with letter A : " + letterResult);

//all numbers can be divided by three
int[] numbers = { 3, 6, 9, 12};
bool iSNumbersDivided = numbers.All(number => number % 3 == 0);
Console.WriteLine($"Numbers are divisible by three = {iSNumbersDivided}");

Working with complex types

//Check whether age of all animals in the zoo is greater than 1 year
bool response = animalData.All(x => x.AnimalAge > 1);
Console.WriteLine($"Is All Animals are greater than 1 years old : {response}");

//get all animas who are feed by milk
var zooSubSet = animalData.Where(x => x.Food.All(y => y.FoodType == "Milk"));
foreach(var item in zooSubSet)
{
    Console.WriteLine($"Animal Name: {item.AnimalName}");
}

Resources

https://stackoverflow.com/questions/959752/where-in-clause-in-linq

https://coderedirect.com/questions/644629/linq-nested-list-contains

Handling custom dataset in C#

I am receiving this dataset from a remote server;

TagNumber	TagCode	CageNumber	FoodType	FoodValue
A-2021-1	WHITE	A9:I10	        Milk	        A11:I
A-2021-1	WHITE	A9:I10	        Corn	        A10:I
A-2021-1	RED	A11:I13	        Meat	        B1:B2
A-2021-1	RED	A11:I13	        Hay	        A14:I
A-2021-1	GREEN	A8:J9	        Milk	        B1:B2
A-2021-1	GREEN	A8:J9	        Milk	        A10:J

I need to create this object, a complex type;

public class Animal
{
    public string TagNumber { get; set; }
    public string TagCode { get; set; }
    public string CageNumber { get; set; }
    public List<AnimalFood> Food { get; set; }
}

public class AnimalFood
{
    public string FoodType { get; set; }
    public string FoodValue { get; set; }
}

There could be many ways to handle this. This is one of them;

Create a dictionary object using LINQ GroupBy and TagCode column from incoming dataset;

var allAnimals = animalData
    .GroupBy(item => item.TagCode)
    .ToDictionary(grp => grp.Key, grp => grp.ToList());

Create unique animals out of dictionary object;

var uniqueAnimals = allAnimals.Keys.Distinct().ToList();

Create the object (animal) and add them to zoo :);

var zoo = new List<Animal>();
foreach (string animal in uniqueAnimals)
{
    var animalRow = allAnimals[animal];
    var animalRowFirst = animalRow.FirstOrDefault();
    var animalRecord = new Animal
    {
         TagNumber = animalRowFirst.TagNumber,
         TagCode = animalRowFirst.TagCode,
         CageNumber = animalRowFirst.CageNumber
    };
    //time for food
    var animalFood = new List<AnimalFood>();
    foreach(var item in animalRow)
    {
        item.Food.ForEach(x =>
        {
            animalFood.Add(new AnimalFood
            {
                  FoodType = x.FoodType,
                  FoodValue = x.FoodValue
            });
        });
    }
   //this is our custom type
   animalRecord.Food = animalFood;
   zoo.Add(animalRecord);
}

Sample output;

It’s easier to apply different filters on this object;

var animalFilter = zoo.Where(x => x.TagCode.ToUpper() == "WHITE");

Resources

https://stackoverflow.com/questions/3186818/unique-list-of-items-using-linq

Different ways to check a null object

C# provides various ways to check for a null object.

Let’s create a class to test;

public class UserObject
{
    public int Id { get; set; }
    public string? Name { get; set; }
}

The most conventional way to check for null is by equating the object with null.

UserObject userObject = null;
//Conventional way to check for null
if (userObject == null)
{
    userObject = new UserObject();
    Console.WriteLine("userObject null - handled using conventional manner");
}

if (userObject != null)
{
    Console.WriteLine("userObject not null - handled using conventional manner");
}

C#7 introduced a new way to write the above code in a more readable way by using the is keyword.

//C#7 introduces a new way 
userObject = null;
if (userObject is null)
{
    userObject = new UserObject();
    Console.WriteLine("userObject null - handled using c#7");
}

The same code can be written using null-coalescing operator.

//we can write the same code using null-coalescing operator
userObject = null;
userObject = userObject ?? new UserObject();
Console.WriteLine("userObject null - handled using null-coalescing operator");

C#9 introduced a new way to write the above code in a more readable way by using the is not keyword.

//C#9 introduces a new way 
if (userObject is not null)
{
    userObject = new UserObject();
    Console.WriteLine("userObject not null - handled using c#9");
}

Hope, this helps.

C# Design Pattern

Design pattern provides a general reusable solution for the common problems that occur in software design. The pattern typically shows relationships and interactions between classes or objects

These patterns are categorized into Structure, Creation and Behavior. This is a list of design pattern and their practical implementations.

Template Method Design Pattern

In simple words, a template method design pattern is a behavioral design pattern that defines the basic skeleton (steps) of an algorithm. In this pattern, we can change the behavior of individual steps in the derived class but can not change the sequence by which each method will be called

The real world examples are;

Making a burger

Builder Pattern

As the name suggests, this design pattern is used to build complex objects in a step by step approach. Using the same construction process we can make different representations of the object.

Suppose we have to build an object with a lot of different configurations based on a scenario. For example, we have to send an Email where we have optional properties like CC (carbon copy), BCC (blind carbon copy), attachments etc.

The real world examples are;

Sending emails

JavaScript frequently used functions

This is a handy reference for frequently used JavaScript functions;

Shorten the console log

Instead of writing console.log() again and again in code, we can bind it;

//tired of typeing console.log. shorten it
    const log = console.log.bind(document);
    log("does it works?");
    log("yes");

Merge two arrays into one

If you want to merge two arrays of any size into a single array you can use the concate JavaScript function.

//merge two arrays
    const array1 = ["one", "two", "three"]
    const array2 = ["four", "five", "six"]

    const merged = array1.concat(array2)
    console.log(merged)
    //Output:
    //(6) ['one', 'two', 'three', 'four', 'five', 'six']

Merge two objects into one

If you working with objects you can merge them together with this simple trick.

//merge two objects into one
    const user = {
        name: "Shahzad",
        gender: "Male"
    };
    const artcile = {
        title: "Born on the Fourth of July",
        publishDate: "12/14/2021"
    };
    const summary = {...user, ...artcile}
    console.log(summary)
    //Output:
    /*
    gender: "Male"
    name: "Shahzad"
    publishDate: "12/14/2021"
    title: "Born on the Fourth of July"
    */

Shorten an array

There exist an easy way for web developers to shorten an array. You need to use the length method and pass a number that is smaller than the actual array size.

//shorten an array
    const big_array = ["one", "two", "three", "four", "five", "six"]
    big_array.length = 3
    console.log(big_array)
    //Output:
    //(3) ['one', 'two', 'three']

Shuffle an array

Sometimes you want to randomize the values within an array. To achieve this you can use the Array.sort function with a random compareFunction.

//shuffle an array
    const array = ["one", "two", "three", "four", "five", "six"]
    array.sort( function(){ return Math.random() - 0.5})
    console.log('shuffling array')
    console.log(array)

Use isNum to verify a number

With this function, you can check whether a value or variable is a number (int, float, etc) or not.

//use isNum to verify Number
    function isNum(n) {return !isNaN(parseFloat(n)) && isFinite(n);}

    console.log(isNum(4125))        //true
    console.log(isNum(50))          //true
    console.log(isNum("jQuery"))    //false

Use isStr to verify a string

With this function, you can check whether a value or variable is in string format or not.

//use isStr to verify string
    const isStr = value => typeof value === 'string';

    console.log(isStr("jQuery"))    //true
    console.log(isStr(4125))        //false
    console.log(isStr(true))        //false

Use isNull

Often it is useful to check if a result or data is null.

//use isNull
    const isNull = value => value == null || value === undefined;

    console.log(isNull(null))   //true
    console.log(isNull())       //true
    console.log(isNull(123))    //false
    console.log(isNull("s"))    //false

Calculate the performance of a function

If you want to check how long a function runs you can use this approach in your program.

//Calculate the performance of a function
    const start = performance.now();
    //business program
    const end = performance.now();
    const total = start - end
    console.log("function takes " + total + " milisecond");

Remove duplicates from an array

We often encounter an array with duplicated data in it and use a loop to remove those duplicates. This function can remove duplicates in an easy way without using a loop.

//Remove duplicates from an array
    const duplicate_array = array => [...new Set(array)]
    console.log(duplicate_array([
        "One", "Two", "Three", "Two", "Four",
        "One", "Two", "Three", "Two", "Five",
        "Three", "One", "Four", "Two", "Five"]))

    //Output:
    //(5) ['One', 'Two', 'Three', 'Four', 'Five']

Use logical AND/OR for conditions

Instead of using an if-condition, you can use a logical AND/OR. This can be used within a function for executing commands.

//Use logical AND/OR for conditions
    const input = 2
    input == 4 && console.log("it is 4")
    input == 4 || console.log("it is not 4")

    //can also be used for assigning values
    function defaultTo4(arg) {
        arg = arg || 4; //arg will have 4 as a default value if not set
        console.log(arg)
    }
    let arg1 = 2
    let arg2 = null
    defaultTo4(arg1)    //2
    defaultTo4(arg2)    //4

Ternary operator

The ternary operator is just cool. You can avoid bad-looking nested conditional if..elseif..elseif with ternary operators.

//Ternary operator
    function temperature(temp){
        return (temp > 39 || temp < 35.5) ? 'Stay home'
        : (temp < 37.5 && temp > 36.5) ? 'Go out and play'
        : (temp <= 39 && temp >= 35.5) ? 'Take some rest'
        : ''
    }

    console.log(temperature(38))    //take some rest
    console.log(temperature(36))    //take some rest
    console.log(temperature(39.1))  //Stay home
    console.log(temperature(35.1))  //Stay home
    console.log(temperature(37))    //Go out and plan

Resources

https://docs.microsoft.com/en-us/javascript/