Language Integrated Query (LINQ)

LINQ extends the language by the addition of query expressions, which are similar character to SQL statements and can be used to conveniently extract and process data from arrays, enumerable classes, XML documents, relational databases and third-party data sources. 

SQL is a Structured Query Language used to save and retrieve data from a database. In the same way, LINQ is a structured query syntax built in C# and VB.NET to retrieve data from different types of data sources such as collections, ADO.Net DataSet, XML Docs, web service and MS SQL Server and other databases.

LINQ queries return results as objects. It enables you to uses object-oriented approach on the result set and not to worry about transforming different formats of results into objects.

Advantages of LINQ
Familiar language: Developers don’t have to learn a new query language for each type of data source or data format.
Less coding: It reduces the amount of code to be written as compared with a more traditional approach.
Readable code: LINQ makes the code more readable so other developers can easily understand and maintain it.
Standardized way of querying multiple data sources: The same LINQ syntax can be used to query multiple data sources.
Compile time safety of queries: It provides type checking of objects at compile time.
IntelliSense Support: LINQ provides IntelliSense for generic collections.
Shaping data: You can retrieve data in different shapes.

We can write LINQ queries for the classes that implement IEnumerable<T> or IQueryable<T> interface.
The Enumerable and Queryable are two static classes that contain extension methods to write LINQ queries.
Enumerable :-
The Enumerable class includes extension methods for the classes that implement IEnumerable<T> interface. 
IEnumerable<T> type of collections are in-memory collection like List, Dictionary, SortedList, Queue, HashSet, LinkedList.
Queryable :-
The Queryable class includes extension methods for classes that implement IQueryable<t> interface.
The IQueryable<T> interface is used to provide querying capabilities against a specific data source where the type of the data is known.
The static Queryable class includes extension methods for classes that implements the IQueryable<T> interface.

There are APIs available to access third party data; for example, LINQ to Amazon provides the ability to use LINQ with Amazon web services to search for books and other items. This can be achieved by implementing the IQueryable interface for Amazon.

C# 3.0(.NET 3.5) introduced the lambda expression along with LINQ. The lambda expression is a shorter way of representing anonymous method using some special syntax.
Example for Lambda Expression in C# :- 
s  =>  s.Age > 12  &&  s.Age < 20




Standard Query Operators in LINQ :- 

Standard Query Operators in LINQ are actually extension methods for the IEnumerable<T> and IQueryable<T> types. They are defined in the System.Linq.Enumerable and System.Linq.Queryable classes. Standard Query Operators can be classified based on the functionality they provide. 

The following are the classification of Standard Query Operators:-

Classification  |  Standard Query Operators
Filtering-         Where, OfType
Sorting-         OrderBy, OrderByDescending, ThenBy, ThenByDescending, Reverse
Grouping- GroupBy, ToLookup
Join- GroupJoin, Join
Projection- Select, SelectMany
Aggregation- Aggregate, Average, Count, LongCount, Max, Min, Sum
Quantifiers- All, Any, Contains
Elements- ElementAt, ElementAtOrDefault, First, FirstOrDefault, Last, LastOrDefault, Single,SingleOrDefault
Set-         Distinct, Except, Intersect, Union
Partitioning- Skip, SkipWhile, Take, TakeWhile
Concatenation-Concat
Equality-         SequenceEqual
Generation- DefaultEmpty, Empty, Range, Repeat
Conversion- AsEnumerable, AsQueryable, Cast, ToArray, ToDictionary, ToList


The following are the operators  available in LINQ :-

Where -         Returns values from the collection based on a predicate function.
OfType  -         Returns values from the collection based on a specified type. However, it will depend on their ability to cast to a specified type.
OrderBy - Sorts the elements in the collection based on specified fields in ascending or descending order.
OrderByDescending -Sorts the collection based on specified fields in descending order. Only valid in method syntax.
ThenBy  - Only valid in method syntax. Used for second level sorting in ascending order.
ThenByDescending-Only valid in method syntax. Used for second level sorting in descending order.
Reverse  - Only valid in method syntax. Sorts the collection in reverse order.
GroupBy - The GroupBy operator returns groups of elements based on some key value. Each group is represented by IGrouping<TKey, TElement> object.
ToLookup - ToLookup is the same as GroupBy; the only difference is the execution of GroupBy is deferred whereas ToLookup execution is immediate.
Join  -         The Join operator joins two sequences (collections) based on a key and returns a resulted sequence.
GroupJoin - The GroupJoin operator joins two sequences based on keys and returns groups of sequences. It is like Left Outer Join of SQL.
All -                 Checks if all the elements in a sequence satisfies the specified condition
Any -         Checks if any of the elements in a sequence satisfies the specified condition
Contains - Checks if the sequence contains a specific element
Aggregate - Performs a custom aggregation operation on the values in the collection.
Average - calculates the average of the numeric items in the collection.
Count -         Counts the elements in a collection.
LongCount - Counts the elements in a collection.
Max -         Finds the largest value in the collection.
Min -         Finds the smallest value in the collection.
Sum -         Calculates sum of the values in the collection.
ElementAt - Returns the element at a specified index in a collection
ElementAtOrDefault- Returns the element at a specified index in a collection or a default value if the index is out of range.
First -         Returns the first element of a collection, or the first element that satisfies a condition.
FirstOrDefault - Returns the first element of a collection, or the first element that satisfies a condition. Returns a default value if index is out of range.
Last -         Returns the last element of a collection, or the last element that satisfies a condition
LastOrDefault-Returns the last element of a collection, or the last element that satisfies a condition. Returns a default value if no such element exists.
Single -         Returns the only element of a collection, or the only element that satisfies a condition.
SingleOrDefault- Returns the only element of a collection, or the only element that satisfies a condition. Returns a default value if no such element exists or the collection does not contain exactly one element.
Last -         Returns the last element from a collection, or the last element that satisfies a condition
LastOrDefault-Returns the last element from a collection, or the last element that satisfies a condition. Returns a default value if no such element exists.
Single -         Returns the only element from a collection, or the only element that satisfies a condition. If Single() found no elements or more than one elements in the collection then throws InvalidOperationException.
SingleOrDefault-The same as Single, except that it returns a default value of a specified generic type, instead of throwing an exception if no element found for the specified condition. However, it will thrown InvalidOperationException if it found more than one element for the specified condition in the collection.
Empty -         Returns an empty collection
Range -         Generates collection of IEnumerable<T> type with specified number of elements with sequential values, starting from first element.
Repeat -         Generates a collection of IEnumerable<T> type with specified number of elements and each element contains same specified value.
Distinct -         Returns distinct values from a collection.
Except -         Returns the difference between two sequences, which means the elements of one collection that do not appear in the second collection.
Intersect -     Returns the intersection of two sequences, which means elements that appear in both the collections.
Union -         Returns unique elements from two sequences, which means unique elements that appear in either of the two sequences.
Skip -         Skips elements up to a specified position starting from the first element in a sequence.
SkipWhile - Skips elements based on a condition until an element does not satisfy the condition. If the first element itself doesn't satisfy the condition, it then skips 0 elements and returns all the elements in the sequence.
Take -         Takes elements up to a specified position starting from the first element in a sequence.
TakeWhile - Returns elements from the first element until an element does not satisfy the condition. If the first element itself doesn't satisfy the condition then returns an empty collection.
AsEnumerable-Returns the input sequence as IEnumerable<t>
AsQueryable - Converts IEnumerable to IQueryable, to simulate a remote query provider
Cast -         Coverts a non-generic collection to a generic collection (IEnumerable to IEnumerable<T>)
OfType -         Filters a collection based on a specified type
ToArray -         Converts a collection to an array
ToDictionary -  Puts elements into a Dictionary based on key selector function
ToList -         Converts collection to List
ToLookup - Groups elements into an Lookup<TKey,TElement>

Electronic Data Interchange - EDI‎

Electronic data interchange  is a standardized, automated method to communicate business information electronically, rather than using paper documents. With EDI, the information moves directly from a computer application in one organization to an application in another.



EDI transmissions can be broken down into two basic types:

1. Point-to-point or direct connections. Two computers or systems connect with no intermediary over the 
    internet, generally with secure protocols.
2. Value-added network (VAN). A third-party network manages data transmission, generally with a mail 
    boxing paradigm.


As an automation technology, EDI delivers core business benefits:

1. Saves time and money. Automates a process previously manually executed with paper documents.
2. Improves efficiency and productivity. More business documents are shared and processed in less time.
3. Reduces errors. EDI’s rigid standardization helps ensure that information and data is correctly formatted 
    before it enters business processes or applications.
4. Improves traceability and reporting. Electronic documents can be integrated with a range of IT systems to
    support data collection, visibility and analysis.
5. Supports positive customer experiences. Enables efficient transaction execution and prompt, reliable 
    product and service delivery.


EDI is important to both large and small businesses - For large organizations, EDI enables standards to be instituted across trading partners to consistently achieve benefits. For smaller organizations, adherence to EDI offers greater integration with larger firms that have big budgets and strong influence.

Metalanguages like Extensible Markup Language (XML) or JavaScript Object Notation (JSON), and application programming interface (API) integration complement, rather than replace EDI


Effective EDI

There are some basic conditions, capabilities and resources needed to implement EDI effectively. In addition to obvious factors like agreement on document types, secure transmission methods, and requisite hardware and software, an effective EDI implementation should consider:

1. Translation or mapping software. Takes fields such as names, addresses, currency amounts, part 
    numbers and quantities, and maps them from business application formats into standardized documents 
    and vice versa.
2. Batch enveloping or developing capabilities. Supports large EDI message batches to enable senders and
    receivers to wrap and unwrap transactions which can then be grouped from or split to several divisions or
    areas of a trading partner’s business.
3. Message routing mechanisms. Required once a message is developed to sort messages for different 
    groups and deliver them to the appropriate targets. Message transformation may also be required to get 
    the message into the correct format for its destination.
4. Trading partner agreements (TPA). Clarifies terms and conditions, establishes standards for business 
    documents and defines communications and business protocols between trading partners.


The future of EDI

In future supply chains, EDI will be the core document exchange capability to support innovations like the Internet of Things (IoT), block chain and artificial intelligence (AI). Future EDI will use:

1. IoT sensors:-  Incorporated into the shipment’s packaging and tied to periodic EDI 214 messages to 
    improve package condition visibility in near real time.
2. Block chain technology:-  Underpinning EDI information flows for shipments can offer a shared version of
    the truth to help quickly resolve and even avoid charge back disputes.
3. AI agent:-  Monitors all relevant events and information connected to the shipment, and can identify a 
    non-compliant event, determine if a reshipment is required, analyze the most efficient source of 
    replacement, initiate a new shipment and an authorized return.


Mail Message

           MailMessage mm = new MailMessage("teztag.web1@gmail.com", "teztag.web2@gmail.com");
            mm.Subject = "Password";
            mm.Body = "body";
            mm.IsBodyHtml = true;
            SmtpClient smtp = new SmtpClient();
            smtp.Host = "smtp.gmail.com";
            smtp.EnableSsl = true;
            System.Net.NetworkCredential NetworkCred = new System.Net.NetworkCredential();
            NetworkCred.UserName = "teztag.web1@gmail.com";
            NetworkCred.Password = "password";
            smtp.UseDefaultCredentials = true;
            smtp.Credentials = NetworkCred;
            smtp.Port = 587;
            smtp.Send(mm);

Check this link
https://myaccount.google.com/lesssecureapps?pli=1
& change the setting as bellow:-
Allow less secure apps: ON

What is a CI/CD pipeline ?

A continuous integration and continuous deployment (CI/CD) pipeline is a series of steps that must be performed in order to deliver a new version of software. CI/CD pipelines are a practice focused on improving software delivery throughout the software development life cycle via automation. 

By automating CI/CD throughout development, testing, production, and monitoring phases of the software development lifecycle, organizations are able to develop higher quality code, faster. Although it’s possible to manually execute each of the steps of a CI/CD pipeline, the true value of CI/CD pipelines is realized through automation.

By automating the process, the objective is to minimize human error and maintain a consistent process for how software is released. Tools that are included in the pipeline could include compiling code, unit tests, code analysis, security, and binaries creation.

CI/CD is the backbone of a DevOps methodology, bringing developers and IT operations teams together to deploy software.



Traditional CI/CD systems are designed for pipelines that use virtual machines, but cloud-native application development brings advantages to CI/CD pipelines.

Generating model from existing database in Asp.Net Core Application

Use NuGet search to Install the same version 8.0.4(exmple) of all the bellow 3 - 
Microsoft.EntityFrameworkCore.Design
Microsoft.EntityFrameworkCore.Tools
Microsoft.EntityFrameworkCore.SqlServer


                               OR


Try    ->
         

PM> 
     1) Install-Package  Microsoft.EntityFrameworkCore.Design
     2) Install-Package  Microsoft.EntityFrameworkCore.Tools
     3) Install-Package  Microsoft.EntityFrameworkCore.SqlServer


                                Then


PM> 
Scaffold-DbContext "Server=Server Name;Initial Catalog=DBname;Persist Security Info=False;
User ID=**;Password=*****;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=
True;Connection Timeout=30;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models  -force

or

Scaffold-DbContext "Server=Server Name;Initial Catalog=DBname;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models
___________________________________________________________________________________
If you done some changes in DB, then try to update the code by using the following;

PM>
Scaffold-DbContext "Server=Server Name;Database=DBname;User ID=**;Password=*****; Trusted_Connection=True;encrypt=false;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models -Force

ASP.NET Core Features

ASP.NET is one of the most successful web application development frameworks by Microsoft. 
With every update, new and extended features are added that help developers deploy highly scalable and high-performance web applications.


Features to build better applications with ASP.NET Core are : -

1. Cross-platform & container support
With the introduction of .NET Core, you can now create ASP.NET applications and deploy them to Windows, Linux and macOS.

2. High performance
The introduction of ASP.NET Core and the Kestrel web server, ASP.NET is touted as one of the fastest web application frameworks available.
The new Kestrel web server was redesigned from the ground up to take advantage of asynchronous programming models, be much more lightweight and fast.

3. Asynchronous via async/await
One of the reasons ASP.NET Core is faster is its extensive use of asynchronous patterns within the new MVC and Kestrel frameworks.
//mark the method as async
public async Task GetGWB()
{
    HttpClient hc = new HttpClient();
    //await keyword handles all the complexity of async threading and callbacks
    await hc.GetAsync("http://geekswithblogs.net/Default.aspx");
    return true;
}

4. Unified MVC & Web API frameworks
MVC was tailored to creating web applications that served up HTML. 
Web API was designed to create RESTful services using JSON or XML.
With ASP.NET Core, MVC and Web API have been merged together. MVC could always return JSON data instead of HTML.
ASP.NET Core are sort of a replacement for WebForms while using the familiar Razor syntax.

5. Dependency Injection
It is the preferred way that things like logging contexts, database contexts and other things are passed into your MVC controllers.
public class PaymentService: IPaymentService
{
  public ILogger Logger { get; }
  //automatically passes the logger factory in to the constructor via dependency injection
  public PaymentService(ILoggerFactory loggerFactory)
  {
    Logger = loggerFactory?.CreateLogger();
    if(Logger == null)
    {
      throw new ArgumentNullException(nameof(loggerFactory));
    }
    Logger.LogInformation("PaymentService created");
  }
}

6. WebSockets & SignalR
ASP.NET has first class support for WebSockets. 
This can be used to persist long running connections and communicate back and forth with the browser. 
SignalR is a full framework that is also available that makes it easy handle common scenarios.

7. Cross-Site Request Forgery (CSRF) Protection
CSRF is in referencing to hijacking users authenticated session to perform an action that they did not initiate.
For example, let’s pretend that you log in to your bank account and then navigate to a different website. If that other website could do a POST to your bank website to transfer funds, that would be a bad thing. It could potentially do that if your online session on the banking website is valid and the bank does not properly validate requests.
ASP.NET has a good framework that is available to prevent these types of attacks. It generates anti-forgery tokens.

8. “Self hosted” Web Applications
Sometimes you need to make a web application that will be deployed on to a desktop and not a server running IIS. 
Our free ASP.NET profiler, Prefix is a perfect example of this. 
Its front end is all HTML that is loaded from an ASP.NET application running as a Windows Service.
You can create a self-hosted ASP.NET web application several different ways. 
In .NET 4.5 you could accomplish it by using Owin, Nancy or WCF. 

9. Action Filters
One of the great features of ASP.NET is the support for extensible filters. This allows you to implement functionality that can be applied to an entire controller or action without modifying the action itself.
Filters are used to specify caching, error handling, authorization or any custom logic you would like to implement.
using System;
using System.Web.Mvc;
namespace MvcApplication1.Controllers
{
     public class DataController : Controller
     {
          [OutputCache(Duration=10)]
          public string Index()
          {
               return DateTime.Now.ToString("T");
          }
     }
}

10. Extensible Output Caching
This feature allows ASP.NET to cache the output generated by a page and serve this cached content for future requests. 
It stores the data that is not updated frequently and outputs that specific data from a cached location.

11. Globalization and Localization
ASP.NET makes it easy to localize dates, numbers and the text within your web application. 
If you want your application to be used across the globe, localization will be very important to you.
ASP.NET enables customizing your application for multiple languages via resource files. These resource files are considered as the central repository where all texts are kept and web pages can read this resource file and get labels populated. There are two types of resources:
Local Resources – specific for a page (i.e., there will be local resource file for every page)
Global Resources – common for the whole website (i.e., one resource file accessed by all pages)

12. Swagger OpenAPI
If you are creating API applications, you want to make sure you are using Swagger. 
It makes it easy to document and test your APIs.
ASP.NET has historically provided built-in functionality that is pretty similar for SOAP web services created with WCF. 
If you are using Web API or MVC for RESTful APIs, you definitely want to use Swagger.

Microsoft SQL Server vs Microsoft SQL Server Management Studio

What is Microsoft SQL Server? 
A relational database management system developed by Microsoft. SQL Server is a database management and analysis system for data warehousing solutions.

What is Microsoft SQL Server Management Studio? 
An integrated environment for managing any SQL infrastructure. It is an integrated environment for managing any SQL infrastructure, from SQL Server to Azure SQL Database. It provides tools to configure, monitor, and administer instances of SQL Server and databases. Use it to deploy, monitor, and upgrade the data-tier components used by your applications, as well as build queries and scripts.

Microsoft SQL Server belongs to "Databases" category of the tech stack, while Microsoft SQL Server Management Studio can be primarily classified under "Database Tools".

SQL Server Management Studio (SSMS) is a software application first launched with Microsoft SQL Server 2005 that is used for configuring, managing, and administering all components within Microsoft SQL Server.
A central feature of SSMS is the Object Explorer, which allows the user to browse, select and act upon any of the objects within the server.

Microsoft SQL Server is a relational database management system developed by Microsoft. As a database server, it is a software product with the primary function of storing and retrieving data as requested by other software applications—which may run either on the same computer or on another computer across a network (including the Internet).

Method Overloading And Method Overriding

Method overloading

Creating more than one method or a function that has a same name but different signatures or parameters in the same class is called method overloading.

Key points
Method overloading is also called  early binding or compile time polymorphism or static binding.
The compiler automatically calls the required method or the function by checking number of parameters and their type, which are passed into that method.
If the number of parameters and type doesn't match by any method signatures, then it will give the compile time error.
We can achive method overloading by changing the number of parameters used or by using different types of parameters or by changing the order of parameters

Example :- 
using System;  
using System.Collections.Generic;  
using System.Text;  
namespace MethodOverloadingDemo  
{  
    class Calculator  
    {  
        //two int type Parameters method    
        public int Add(int x, int y)  
        {  
            int p;  
            return p=x + y;  
        }  
        //three int type Parameters method    
        public int Add(int x, int y,int z)  
        {  
            int q;  
            return q = x + y + z;  
        }  
        //two float type Parameters method    
        public float Add(float x, float y)  
        {  
            float r;  
            return r = x + y;  
        }            
        //three float type Parameters method    
        public float Add(float x, float y, float z)  
        {  
            float v;  
            return v = x + y + z;  
        }  
    }  
     
    class calculatorDemo  
    {  
    public static void Main(String[] args)  
    {  
           Calculator calculator = new Calculator();  
           calculator.Add(10,20);  
           calculator.Add(10,20,30);  
           calculator.Add(10f,20f);  
           calculator.Add(10f,20f,30f); 
           Console.ReadLine();  
    }  
    }  
}   



Method overriding

Creating a method in the derived class with same signature as a method in the base class is called method overriding
or
Method overriding means having two methods with the same name and same signature, one method in the base class and the other method in the derived class.

Key points
Method overriding is also called run time polymorphism or dynamic polymorphism or late binding.
We can override a method in the base class by creating similar function in the derived class. This can be achieved by using inheritance and using virtual & override.
Same signature means the methods must have the same name, same number of arguments and same type of arguments.
Method overriding is possible only in the derived classes, but not within the same class.
When the derived class needs a method with the same signature as in the base class, but wants to execute different code than the one provided by the base class then method overriding will be used.

Important keywords in method overriding

1. Virtual keyword
If we use Virtual keyword, then we tell to compiler that this method can be overridden by the derived classes.
public virtual int Print()  
{  
   //Implementation of Print method in Base class  
2. Override keyword
If we use Overrride keyword, then we tell to the compiler that this method is overriding the same named method in the base class.
public override int Print()  
{  
   //Implementation of Print method in Derived class  
}  
3. Base keyword
If we use base keyword, then we tell to the compiler that this method calls the base class method for overriding functionality.
base.Print();  

Comparison between method overloading and method overriding:-


Method Overloading

Method Overriding

1.

Creating more than one method or function having same name but different signatures or the parameters in the same class is called method overloading.

Creating a method in the derived class with the same signature as a method in the base class is called as method overriding

2.

It is called the compile time polymorphism

It is called runtime polymorphism

3.

It has the same method name but with different signatures or the parameters

It must have same method name as well as the signatures or the parameters.

4.

Method overloading doesn’t need inheritance

Mehod overriding needs inheritance

5.

Method overloading is possible in single class only

Method overriding needs hierachy level of the classes i.e. one parent class and other child class.

6.

Access modifier can be any

Access modifier must be public.

7.

Method overloading is also called early binding.

Method overriding is also called late binding.


Abstraction in C#

Abstraction defined as the process of identifying only the required characteristics of an object ignoring the irrelevant details.
The properties and behaviors of an object differentiate it from other objects of similar type and also help in classifying/grouping the objects.

Example: 
Consider a real-life scenario of withdrawing money from ATM. 
The user only knows that in ATM machine first enter ATM card, then enter the pin code of ATM card, and then enter the amount which he/she wants to withdraw and at last, he/she gets their money. 
The user does not know about the inner mechanism of the ATM or the implementation of withdrawing money etc. 
The user just simply know how to operate the ATM machine, this is called abstraction.

In C#, abstraction is achieved with the help of Abstract classes.
Abstract Classes
-An abstract class is declared with the help of abstract keyword.
-In C#, you are not allowed to create objects of the abstract class. Or in other words, you cannot use the abstract class directly with the new operator.
-Class that contains the abstract keyword with all of its methods is known as pure Abstract Base Class.
-You are not allowed to declare the abstract methods outside the abstract class.
-You are not allowed to declare abstract class as Sealed Class.

There are situations in which we want to define a superclass that declares the structure of a given abstraction without providing a complete implementation of every method. 
That is, sometimes we want to create a superclass that only defines a generalized form that will be shared by all of its subclasses, leaving it to each subclass to fill in the details.
Consider a classic “shape” example, perhaps used in a computer-aided design system or game simulation. 
The base type is “shape” and each shape has a color, size and so on. 
From this, specific types of shapes are derived(inherited)-circle, square, triangle and so on – each of which may have additional characteristics and behaviors. 

The following are some of the key points −
You cannot create an instance of an abstract class.
You cannot declare an abstract method outside an abstract class.
When a class is declared sealed, it cannot be inherited, abstract classes cannot be declared sealed.


Example

using System;
namespace Demo {
   abstract class Shape {
      public abstract int area();
   }
   
   class Rectangle:  Shape {
      private int length;
      private int width;
      
      public Rectangle( int a = 0, int b = 0) {
         length = a;
         width = b;
      }
      public override int area () { 
         Console.WriteLine("Rectangle class area :");
         return (width * length); 
      }
   }
   class RectangleTester {
      static void Main(string[] args) {
         Rectangle r = new Rectangle(20, 15);
         double a = r.area();
         Console.WriteLine("Area: {0}",a);
         Console.ReadKey();
      }
   }
}

Output-
Rectangle class area :
Area: 300

List vs Dictionary in C#

Both lists and dictionaries belong to Generics collections that is they used to store collections of data. 
Both Dictionary <TKey, TValue> and List <T> are similar both have the random access data structures on top of the .NET framework. 
The Dictionary is based on a hash table that means it uses a hash lookup, which is an efficient algorithm to look up things, on the other hand, a list, have to go and check element by element until it finds the result from the beginning. 

The Dictionary uses the hashing algorithm to search for the element (data). 
A Dictionary first calculates a hash value for the key and this hash value leads to the target data bucket. 
After that, each element in the bucket needs to be checked for equality. 
But actually, the list will be faster than the dictionary on the first item search because nothing to search in the first step. 
But in the second step, the list has to look through the first item and then the second item. So each step the lookup takes more and more time. 
The larger the list, the longer it takes. 
Of course, the Dictionary in principle has a faster lookup with O(1) while the lookup performance of a List is an O(n) operation.

The Dictionary maps a key to a value and cannot have duplicate keys, whereas a list just contains a collection of values. 
Also, Lists allow duplicate items and support linear traversal.


Consider the following example:

Dictionary<string, int> dictionary = new Dictionary<string, int>();
List<int> newList = new List<int>();
Add data to the list
newList.Add(data);
A list can simply add the item at the end of the existing list item. 

Add data to the Dictionary
dictionary.Add(key, data);
When you add data to a Dictionary, you should specify a unique key to the data so that it can be uniquely identified.


A Dictionary has a unique identifier, so whenever you look up a value in a Dictionary, the runtime must compute a hash code from the key. 
This optimized algorithm implemented by some low-level bit shifting or modulo divisions. 
We determine the point at which Dictionary becomes more efficient for lookups than List.

The Find() method of the List class loops through each object in the list until a match is found. 
So, if we want to lookup a value using a key, then dictionary is better for performance over list. 
So, we need to use dictionary when we know the collection will be primarily used for lookups.