30 April 2024

Linq in C#

Linq in C# 

Language Integrated Query (LINQ) in C# provides a robust syntax for querying collections, whether they are objects in memory (like arrays or lists), or data sources like databases or XML files. One of the powerful features of LINQ is its ability to perform join operations similar to those in SQL. Here, I'll provide examples of different types of joins you can perform using LINQ: inner join, group join, and left outer join.


### Example Data Classes
Before jumping into the join examples, let's define some sample data classes:

```csharp
public class Employee
{
    public int EmployeeID { get; set; }
    public string Name { get; set; }
}

public class Department
{
    public int DepartmentID { get; set; }
    public string Name { get; set; }
}

public class EmployeeDepartment
{
    public int EmployeeID { get; set; }
    public int DepartmentID { get; set; }
}
```

### 1. Inner Join
This join returns only those records where there is a match in both joined tables.

```csharp
var employees = new List<Employee>
{
    new Employee { EmployeeID = 1, Name = "John" },
    new Employee { EmployeeID = 2, Name = "Jane" },
    new Employee { EmployeeID = 3, Name = "Doe" }
};

var departments = new List<Department>
{
    new Department { DepartmentID = 1, Name = "IT" },
    new Department { DepartmentID = 2, Name = "HR" }
};

var employeeDepartments = new List<EmployeeDepartment>
{
    new EmployeeDepartment { EmployeeID = 1, DepartmentID = 1 },
    new EmployeeDepartment { EmployeeID = 2, DepartmentID = 2 }
};

var innerJoinQuery = from emp in employees
                     join empDep in employeeDepartments on emp.EmployeeID equals empDep.EmployeeID
                     join dep in departments on empDep.DepartmentID equals dep.DepartmentID
                     select new
                     {
                         EmployeeName = emp.Name,
                         DepartmentName = dep.Name
                     };

foreach (var item in innerJoinQuery)
{
    Console.WriteLine($"Employee: {item.EmployeeName}, Department: {item.DepartmentName}");
}
```

### 2. Group Join
Group join combines elements from two sequences based on key equality and groups the results.

```csharp
var groupJoinQuery = from dep in departments
                     join emp in employees
                     on dep.DepartmentID equals emp.EmployeeID into deptEmployees
                     select new
                     {
                         DepartmentName = dep.Name,
                         Employees = deptEmployees
                     };

foreach (var dept in groupJoinQuery)
{
    Console.WriteLine($"Department: {dept.DepartmentName}");
    foreach (var emp in dept.Employees)
    {
        Console.WriteLine($" Employee: {emp.Name}");
    }
}
```

### 3. Left Outer Join
A left outer join returns all records from the left table, and the matched records from the right table. If there is no match, the result is `null` on the side of the right table.

```csharp
var leftOuterJoinQuery = from emp in employees
                         join empDep in employeeDepartments
                         on emp.EmployeeID equals empDep.EmployeeID into empDeptResult
                         from subEmpDep in empDeptResult.DefaultIfEmpty()
                         join dep in departments
                         on subEmpDep?.DepartmentID equals dep.DepartmentID into depResult
                         from subDep in depResult.DefaultIfEmpty()
                         select new
                         {
                             EmployeeName = emp.Name,
                             DepartmentName = subDep?.Name ?? "No Department"
                         };

foreach (var item in leftOuterJoinQuery)
{
    Console.WriteLine($"Employee: {item.EmployeeName}, Department: {item.DepartmentName}");
}

GROUP BY in SQL Server

 GROUP BY in SQL Server

In SQL Server, the `GROUP BY` statement is used to arrange identical data into groups. This statement is often used with aggregate functions (like `COUNT`, `MAX`, `MIN`, `SUM`, `AVG`) to perform an operation on each group of data. Here’s a breakdown of how you can use the `GROUP BY` statement effectively in SQL Server, including basic and more advanced uses.


### Basic Example

Suppose you have a table named `Sales` that records the sales figures for different stores:

```sql
CREATE TABLE Sales (
    StoreID int,
    EmployeeID int,
    SaleAmount decimal
);
```

If you want to find the total sales for each store, you could use the `GROUP BY` statement like this:

```sql
SELECT StoreID, SUM(SaleAmount) AS TotalSales
FROM Sales
GROUP BY StoreID;
```

This query groups the rows in the table by the `StoreID` and then calculates the sum of `SaleAmount` for each group.

### Using `GROUP BY` with Multiple Columns

You can also group by more than one column. For example, if you want to find the total sales by each employee within each store, you would write:

```sql
SELECT StoreID, EmployeeID, SUM(SaleAmount) AS TotalSales
FROM Sales
GROUP BY StoreID, EmployeeID;
```

This query groups the data first by `StoreID` and then within each store, it groups by `EmployeeID`.

### Filtering Groups with `HAVING`

The `HAVING` clause is used to filter records that work on summarized `GROUP BY` results. It is different from `WHERE`, which filters rows before grouping.

For instance, to find only those stores where the total sales are greater than $1000, you could use:

```sql
SELECT StoreID, SUM(SaleAmount) AS TotalSales
FROM Sales
GROUP BY StoreID
HAVING SUM(SaleAmount) > 1000;
```

### Complex Example with `JOIN` and `GROUP BY`

Consider you have another table named `Stores` that contains additional information about each store:

```sql
CREATE TABLE Stores (
    StoreID int,
    StoreName varchar(100),
    Location varchar(100)
);
```

If you want to report the total sales for each store along with the store name and location, you would use `JOIN` and `GROUP BY` together:

```sql
SELECT s.StoreName, s.Location, SUM(sa.SaleAmount) AS TotalSales
FROM Sales sa
JOIN Stores s ON sa.StoreID = s.StoreID
GROUP BY s.StoreName, s.Location;
```

This query joins the `Sales` and `Stores` tables on the `StoreID`, then groups the result by `StoreName` and `Location` to calculate total sales.

### Grouping with ROLLUP

To add subtotals and a grand total using `GROUP BY`, you can use `ROLLUP`. For example:

```sql
SELECT StoreID, SUM(SaleAmount) AS TotalSales
FROM Sales
GROUP BY ROLLUP (StoreID);
```

This will provide a subtotal of sales for each `StoreID` and a final row representing the grand total of all sales.

The `GROUP BY` clause in SQL Server is a powerful tool for summarizing data, and by combining it with other SQL features, you can perform complex analyses and reports effectively. Remember to index columns that are frequently grouped by to optimize performance.

Find number of letter occurence of all letter in c#

  Find number of letter occurence of all letter in c#  namespace ConsoleApp1 {     internal class Program     {         static void Main(st...