Extremely Serious

Month: April 2020 (Page 1 of 2)

Class Property

Description

A member of a class that provides flexibility for exposing private fields.

Sample Property Declaration

//backing private field
private string prop;

public string ReadWriteProp {
    get {
        return prop;
    }
    set {
        prop = value;
    }
}

public string ReadOnlyProp {
    get {
        return prop;
    }
}

public string WriteOnlyProp {
    set {
        prop = value;
    }
}

Sample Auto-Implemented Property Declaration

A more concise property declaration especially if theres no additional logic required for the accessors.

public string ReadWriteProp {
    get; set;
} 

public string ReadOnlyProp {
    get; private set;
} 

public string WriteOnlyProp {
    private get; set;
}

The Delegate Type

Definition

Delegate is a type that references methods with a particular parameter list and return type.

Printer Custom Delegate

public delegate void Printer<T>(T data);

A Method for Printer Delegate

static void ConsoleWrite<T>(T data) {
    Console.WriteLine(data);
}

Reference the ConsoleWrite method with Printer delegate

Printer<String> consoleOut = new Printer<String>(ConsoleWrite);
consoleOut("test");

 

The virtual keyword

Usage

The virtual keyword allows to modify a method, property, indexer or event declaration and to be overridden in a derived class.

Example

public virtual double volume() {
   return len * width * height
}

Covariant vs Contravariant

Covariant

The type can vary in the direction as the subclass.

Contravariant

The reverse of covariant.

Example in Generics

Language Covariant Contravariant
C# IList<out T> IList<in T>
Java List<? extends Number> List<? super Integer>

C# Generic Delegates

Description

These are delegates built-in with the framework and ready for your use.

List of Generic Delegates

Delegate NameArgumentsReturnsComment
Actionvoid
Action<T1,T2,T3,T4, T5,T6,T7,T8, T9,T10,T11,T12, T13,T14,T15,T16>(T1,T2,T3,T4, T5,T6,T7,T8, T9,T10,T11,T12, T13,T14,T15,T16)voidThis version of Action delegate can have 1 up to 16 arguments of different types.
Func<TResult>TResult
Func<T1,T2,T3,T4, T5,T6,T7,T8, T9,T10,T11,T12, T13,T14,T15,T16,TResult>(T1,T2,T3,T4, T5,T6,T7,T8, T9,T10,T11,T12, T13,T14,T15,T16)TResultThis version of Func delegate can have 1 up to 16 arguments of different types.
Predicate<T>Tbool

Common Table Expression (CTE) – With Clause

The with clause is also known as common table expression (CTE) and subquery refactory. It is a temporary named result set.

SQL:1999 added the with clause to define "statement scoped views". They are not stored in the database scheme: instead, they are only valid in the query they belong to. This makes it possible to improve the structure of a statement without polluting the global namespace.

Syntax

with <QUERY_NAME_1> (<COLUMN_1>[, <COLUMN_2>][, <COLUMN_N>]) as
     (<INNER_SELECT_STATEMENT>)
[,<QUERY_NAME_2> (<COLUMN_1>[, <COLUMN_2>][, <COLUMN_N>]) as
     (<INNER_SELECT_STATEMENT>)]
<SELECT_STATEMENT>

Non-Recursive Example

with sales_tbl as (
select sales.*
	from (VALUES
		('Spiderman',1,19750),
		('Batman',1,19746),
		('Superman',1,9227),
		('Iron Man',1,9227),
		('Wonder Woman',2,16243),
		('Kikkoman',2,17233),
		('Cat Woman',2,8308),
		('Ant Man',3,19427),
		('Aquaman',3,16369),
		('Iceman',3,9309)
	) sales (emp_name,dealer_id,sales)
)
select ROW_NUMBER() over (order by dealer_id) as rownumber, *
from sales_tbl

Recursive Example

WITH [counter] AS (

   SELECT 1 AS n  -- Executes first and only once.

   UNION ALL      -- UNION ALL must be used.

   SELECT n + 1   -- The portion that will be executed 
   FROM [counter] -- repeatedly until there's no row 
                  -- to return.

   WHERE  n < 50  -- Ensures that the query stops.
)
SELECT n FROM [counter]

SQL Window Functions

Window functions are closely related to aggregate functions except that it retains all the rows.

Categories

Aggregate Window Functions

Ranking Window Functions

Value Window Functions

Example

with sales_tbl as (
select sales.*
	from (VALUES
		('Spiderman',1,19750),
		('Batman',1,19746),
		('Superman',1,9227),
		('Iron Man',1,9227),
		('Wonder Woman',2,16243),
		('Kikkoman',2,17233),
		('Cat Woman',2,8308),
		('Ant Man',3,19427),
		('Aquaman',3,16369),
		('Iceman',3,9309)
	) sales (emp_name,dealer_id,sales)
)
select ROW_NUMBER() over (order by dealer_id) as rownumber,
	*,
	AVG(sales) over (partition by dealer_id) as [Average Sales by DealerID],
	SUM(sales) over (partition by dealer_id) as [Total Sales by DealerID],
	SUM(sales) over (partition by dealer_id order by sales rows between unbounded preceding and current row) as [Running Total by DealerID]
from sales_tbl

Value Window Functions

LAG()

Accesses data from a previous row in the same result set without the use of a self-join starting with SQL Server 2012 (11.x). LAG provides access to a row at a given physical offset that comes before the current row. Use this analytic function in a SELECT statement to compare values in the current row with values in a previous row.

LEAD()

Accesses data from a subsequent row in the same result set without the use of a self-join starting with SQL Server 2012 (11.x). LEAD provides access to a row at a given physical offset that follows the current row. Use this analytic function in a SELECT statement to compare values in the current row with values in a following row.

Common Syntax

LAG | LEAD
( expression )
OVER ( [ PARTITION BY expr_list ] [ ORDER BY order_list ] )

FIRST_VALUE()

Returns the first value in an ordered set of values in SQL Server 2019

LAST_VALUE()

Returns the last value in an ordered set of values in SQL Server 2019 (15.x).

Common Syntax

FIRST_VALUE | LAST_VALUE
( expression ) OVER
( [ PARTITION BY expr_list ] [ ORDER BY order_list ][ frame_clause ] )

Ranking Window Functions

CUME_DIST()

For SQL Server, this function calculates the cumulative distribution of a value within a group of values. In other words, CUME_DIST calculates the relative position of a specified value in a group of values. Assuming ascending ordering, the CUME_DIST of a value in row r is defined as the number of rows with values less than or equal to that value in row r, divided by the number of rows evaluated in the partition or query result set

DENSE_RANK()

This function returns the rank of each row within a result set partition, with no gaps in the ranking values. The rank of a specific row is one plus the number of distinct rank values that come before that specific row.

NTILE()

Distributes the rows in an ordered partition into a specified number of groups. The groups are numbered, starting at one. For each row, NTILE returns the number of the group to which the row belongs.

PERCENT_RANK()

Calculates the relative rank of a row within a group of rows in SQL Server 2019 (15.x). Use PERCENT_RANK to evaluate the relative standing of a value within a query result set or partition. PERCENT_RANK is similar to the CUME_DIST function.

RANK()

Returns the rank of each row within the partition of a result set. The rank of a row is one plus the number of ranks that come before the row in question.

ROW_NUMBER()

Numbers the output of a result set. More specifically, returns the sequential number of a row within a partition of a result set, starting at 1 for the first row in each partition.

Common Syntax

window_function () OVER clause

Aggregate Window Functions

AVG()

This function returns the average of the values in a group

COUNT()

This function returns the number of items found in a group.

MAX()

Returns the maximum value in the expression.

MIN()

Returns the minimum value in the expression

STDEV()

Returns the statistical standard deviation of all values in the specified expression.

STDEVP()

Returns the statistical standard deviation for the population for all values in the specified expression.

SUM()

Returns the sum of all the values, or only the DISTINCT values, in the expression.

VAR()

Returns the statistical variance of all values in the specified expression

VARP()

Returns the statistical variance for the population for all values in the specified expression.

Common Syntax

window_function ( [ ALL ] expression ) 
OVER ( [ PARTITION BY expr_list ] [ ORDER BY order_list frame_clause ] )
« Older posts