==========to be read==========
https://www.c-sharpcorner.com/article/async-and-await-in-c-sharp/
https://www.c-sharpcorner.com/article/task-and-thread-in-c-sharp/
https://learn.microsoft.com/en-us/aspnet/core/fundamentals/middleware/?view=aspnetcore-5.0
https://learn.microsoft.com/en-us/aspnet/core/fundamentals/middleware/write?view=aspnetcore-7.0
https://endjin.com/blog/2022/09/service-lifetimes-in-aspnet-core
https://www.c-sharpcorner.com/UploadFile/a20beb/ienumerable-vs-iqueryable-in-linq/
==================
Differences between Middleware and Filter
Middleware has access to HttpContext but Filter has access to wider MVC Context which helps us to access routing data and model binding information.
Filters are only part of MVC Middleware but middlewares are part of every request pipeline.
The Execution of Middleware occurs before MVC Context becomes available in the pipeline.
Middleware will be executed irrespective of the Controller or Action Method we are hitting but Filters will be executed based on which Controller or Action Method it has been configured.
=======================C# Program=====================
1. Second Highest Value ?
----------------------
int[] myArray = new int[] { 0, 1, 2, 3, 13, 8, 5 };
int first = 0;
int second = 0;
for (int i = 0; i < myArray.Length; i++)
{
if (myArray[i] > first)
{
second = first;
first = myArray[i];
}
else if (myArray[i] > second)
{
second = myArray[i];
}
}
Console.WriteLine(first);
Console.WriteLine("\n");
Console.WriteLine(second);
Array.Sort(myArray);
Array.Reverse(myArray);
Console.WriteLine(myArray[1]);
var temp = (from number in myArray
orderby number descending
select number).Distinct().Skip(1).First();
Console.WriteLine(temp);
var temp1 = myArray.OrderByDescending(x => x).Skip(1).First();
Console.WriteLine(temp1);
2. Number of Repeated value ?
-----------------------------
int[] num = { 1, 2, 3, 2, 2, 1, 4, 5, 6, 1, 1, 1, 1 };
var query = num.GroupBy(x => x)
.Where(g => g.Count() > 1)
.Select(y => new { Element = y.Key, Counter = y.Count() })
.ToList();
foreach (var item in query)
{
Console.WriteLine("Duplicate value : {0}", item.Element);
Console.WriteLine("MaxCount : {0}", item.Counter);
}
IEnumerable<int> duplicates = num.GroupBy(x => x)
.Where(g => g.Count() > 1)
.Select(x => x.Key);
Console.WriteLine("Duplicate elements are: " + String.Join(",", duplicates));
var result = num.GroupBy(x => x).Select(x => new { key = x.Key, val = x.Count() });
foreach (var item in result)
{
if (item.val > 1)
{
Console.WriteLine("Duplicate value : {0}", item.key);
Console.WriteLine("MaxCount : {0}", item.val);
}
}
var temp = num.GroupBy(x => x);
foreach (var group in temp)
Console.WriteLine("Value {0} has {1} items", group.Key, group.Count());
int[] count = new int[10];
//Loop through 0-9 and count the occurances
for (int x = 0; x < 10; x++)
{
for (int y = 0; y < num.Length; y++)
{
if (num[y] == x)
count[x]++;
}
}
//For displaying output only
for (int x = 0; x < 10; x++)
Console.WriteLine("Number " + x + " appears " + count[x] + " times");
################################################################################################################
============================================================Word Duplicate==============================
string str = "this is lazy dog and lazy cat";
var temp = str.Split(" ");
var result = temp.GroupBy(x => x).Where(y => y.Count() > 1).Select(r => new { Word = r.Key, Counter = r.Count() }).ToList();
foreach (var item in result)
{
Console.WriteLine("Duplicate value : {0}", item.Word);
Console.WriteLine("MaxCount : {0}", item.Counter);
}
Output: lazy 2
====================================================================================================================
public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
public int Salary { get; set; }
}
List<Employee> objEmp = new List<Employee>() {
new Employee { Id = 1, Name = "Raj", Salary = 5000 },
new Employee { Id = 2, Name = "Raju", Salary = 9000 },
new Employee { Id = 3, Name = "Ramu", Salary = 3000 },
new Employee { Id = 4, Name = "Ram", Salary = 7000 }};
var temp = objEmp.Where(x => x.Salary > 5000).Select(y => new { y.Name, y.Salary }).ToList();
var teenStudentsName = from s in objEmp
where s.Salary > 5000
select new { Name = s.Name,Salary=s.Salary };
######################################################################################################################
Find Out Common Char
class GFG
{
static int MAX_CHAR = 26;
public static void commonCharacters(String []str,
int n)
{
// primary array for common characters
// we assume all characters are seen before.
Boolean[] prim = new Boolean[MAX_CHAR];
for(int i = 0; i < prim.Length; i++)
prim[i] = true;
// for each string
for (int i = 0; i < n; i++)
{
// secondary array for common characters
// Initially marked false
Boolean[] sec = new Boolean[MAX_CHAR];
for(int s = 0; s < sec.Length; s++)
sec[s]=false;
// for every character of ith string
for (int j = 0; j < str[i].Length; j++)
{
// if character is present in all
// strings before, mark it.
if (prim[str[i][j] - 'a'])
sec[str[i][j] - 'a'] = true;
}
// Copy whole secondary array into primary
Array.Copy(sec, 0, prim, 0, MAX_CHAR);
}
// Displaying common characters
for (int i = 0; i < 26; i++)
if (prim[i])
{
Console.Write((char)(i + 97));
Console.Write(" ");
}
}
// Driver code
public static void Main(String[] args)
{
String []str = { "geeksforgeeks",
"gemkstones",
"acknowledges",
"aguelikes" };
//String []arr ={"bella", "label", "roller"};
//var word = new string[] { "cool", "lock", "cook" };
int n = str.Length;
commonCharacters(str, n);
}
}
OR Short Way
-------------
//var arr = new string[]{"bella", "label", "roller"};
//var word = new string[] { "cool", "lock", "cook" };
//var str1 = arr[0];
//var str2 = arr[1];
//var str3 = arr[2];
//var st1 = word[0];
//var st2 = word[1];
//var st3 = word[2];
//var common = str1.Intersect(str2).Intersect(str3);
//var common1 = st1.Intersect(st2).Intersect(st3);
//foreach (var c in common)
// Console.WriteLine(c); // "i", "r", "e"
===================================================================================
public static Boolean canConstuct(string ransomeNote, string magazine)
{
int[] alphabet = new int[26];
for (int i = 0; i < magazine.Length; i++)
{
alphabet[magazine[i] - 'a'] += 1;
}
for (int j = 0; j < ransomeNote.Length; j++)
{
alphabet[ransomeNote[j] - 'a'] -= 1;
if (alphabet[ransomeNote[j] - 'a'] < 0)
{
return false;
}
}
return true;
}
bool temp= canConstuct("a", "b");
bool temp1 = canConstuct("aa", "ab");
bool temp2 = canConstuct("aa", "aab");
============================================================================================
public static String swap(String a,
int i, int j)
{
char temp;
char[] charArray = a.ToCharArray();
temp = charArray[i];
charArray[i] = charArray[j];
charArray[j] = temp;
string s = new string(charArray);
return s;
}
private static void permute(String str,
int l, int r)
{
if (l == r)
Console.WriteLine(str);
else
{
for (int i = l; i <= r; i++)
{
str = swap(str, l, i);
permute(str, l + 1, r);
str = swap(str, l, i);
}
}
}
String str = "cat";
int n = str.Length;
permute(str, 0, n - 1);
Input : "cat"
Output: cat
cta
act
atc
tac
tca
===================================================================================================
==============================================Pagignation in Linq
List<Employee> objEmp = new List<Employee>() {
new Employee { Id = 1, Name = "Raj", Salary = 5000 },
new Employee { Id = 2, Name = "Raju", Salary = 9000 },
new Employee { Id = 3, Name = "Ramu", Salary = 3000 },
new Employee { Id = 4, Name = "Ram", Salary = 70001 },
new Employee { Id = 5, Name = "Ram2", Salary = 70002 },
new Employee { Id = 6, Name = "Ram3", Salary = 70003 },
new Employee { Id = 7, Name = "Ram4", Salary = 70004 },
new Employee { Id = 8, Name = "Ram5", Salary = 70005 },
new Employee { Id = 9, Name = "Ram6", Salary = 70006 },
new Employee { Id = 10, Name = "Ram7", Salary = 70007 },
new Employee { Id = 11, Name = "Ram8", Salary = 70008 },
new Employee { Id = 12, Name = "Ram9", Salary = 70009 }};
int totalPage = 4;
do {
Console.WriteLine("Eneter Page Number");
if (int.TryParse(Console.ReadLine(), out int pageNumber))
{
var result = objEmp.Skip((pageNumber - 1) * totalPage).Take(totalPage);
foreach (var item in result)
{
Console.WriteLine($"Id= {item.Id} and Name= {item.Name}");
}
}
else
{
Console.WriteLine("Eneter Valid Page");
}
} while (true);
==========================================================================================================================
Example 1:
Input: s = "anagram", t = "nagaram"
Output: true
Example 2:
Input: s = "rat", t = "car"
Output: false
char[] ca = s.ToCharArray();
char[] ct = t.ToCharArray();
Array.Sort(ca);
Array.Sort(ct);
String ss = new String(ca);
String st = new String(ct);
return ss.Equals(st);
============================================================================================================================
===========================================Array Sorting====================================================================
var arr = new int[] { 3, 5, 7, 1, 4 };
int temp = 0;
for (int i = 0; i < arr.Length-1; i++)
{
for (int j = i+1; j < arr.Length; j++)
{
if (arr[i] > arr[j])
{
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
foreach (var item in arr)
{
Console.WriteLine(item);
}
===============================================================================================================================
=========================================================Binary to Decimal===============================
int num, binVal, decVal = 0, baseVal = 1, rem;
num = 101;
binVal = num;
while (num > 0)
{
rem = num % 10;
decVal = decVal + rem * baseVal;
num = num / 10;
baseVal = baseVal * 2;
}
Console.Write("Binary Number: " + binVal);
Console.Write("\nDecimal: " + decVal);
================================================================================================================================
==========================================================Output==========================================
public class ABC
{
public ABC()
{
Console.WriteLine("Constructor ABC");
}
public void abc()
{
Console.WriteLine("Method ABC");
}
}
public class XYZ :ABC
{
public XYZ()
{
Console.WriteLine("Constructor XYZ");
}
public void abc()
{
Console.WriteLine("Method XYZ");
}
}
class Program
{
static void Main(string[] args)
{
XYZ a = new XYZ();
ABC b = a;
a.abc();
}
}
Output : Constructor ABC
Constructor XYZ
Method XYZ
==============================================================================================================================
================================================================Output
public class ABC
{
public void abc(int x)
{
Console.WriteLine("Method ABC");
}
}
public class XYZ :ABC
{
public void abc(double y)
{
Console.WriteLine("Method XYZ");
}
}
class Program
{
static void Main(string[] args)
{
XYZ x = new XYZ();
x.abc(2);
Console.ReadLine();
}
}
Output : XYZ
===============================================================================================================================
========================================================================Output==============================
static void Main(string[] args)
{
int someValue;
Method2(out someValue);
Method1(ref someValue);
Method(someValue);
Console.WriteLine(someValue); // 1
Console.WriteLine(someValue); // 1
Console.WriteLine(someValue); // 1
Console.ReadLine();
}
static void Method(int val)
{
val = 0;
}
static void Method1(ref int val)
{
val = 1;
}
static void Method2(out int val)
{
val = 2;
}
================================================================================================================================
=============================================================Output==============================
int val=15;
Console.WriteLine(val++); //15
Console.WriteLine(++val); //17
Console.WriteLine(val); //17
Console.WriteLine("*********");
Console.WriteLine(val--); //17
Console.WriteLine(--val); //15
Console.WriteLine(val); //15
Console.WriteLine(++val); //16
Console.WriteLine(val++); //16
Console.WriteLine(val); //17
Console.WriteLine("*********");
Console.WriteLine(--val); //16
Console.WriteLine(val--); //16
Console.WriteLine(val); //15
===============================================================================================================================
============================================================Output===============================
public class XX
{
public XX()
{
Console.WriteLine("Constructor XX");
}
public XX(int x)
{
Console.WriteLine("Constructor XX1");
}
}
public class YY:XX
{
public YY():base(1)
{
Console.WriteLine("Constructor YY");
}
}
class Program
{
static void Main(string[] args)
{
YY y = new YY();
Console.ReadLine(); // Output: Constructor XX1
Constructor YY
}
}
===============================================================================================================================
======================================================Output=========================================================
public class ABC
{
public void show(int x)
{
Console.WriteLine("From ABC");
}
}
public class XYZ : ABC
{
public void show(double y)
{
Console.WriteLine("From XYZ");
}
}
class Program
{
static void Main(string[] args)
{
XYZ b = new XYZ();
b.show(2); // Output : From XYZ
Console.ReadLine();
}}
=================================================================================================================================
======================================================Output===================
public class P
{
}
public class Q:P
{
}
public class ABC
{
public void show(Q q)
{
Console.WriteLine("From ABC");
}
}
public class XYZ : ABC
{
public void show(P p)
{
Console.WriteLine("From XYZ");
}
}
class Program
{
static void Main(string[] args)
{
XYZ b = new XYZ();
b.show(new Q()); // Output : From XYZ
Console.ReadLine();
}}
================================================================================================================================
==========================================================Output=====================================================
public class P
{
}
public class Q:P
{
}
public class ABC
{
public ABC(int y)
{
Console.WriteLine("Constructor ABC");
}
public void show(Q q)
{
Console.WriteLine("From ABC");
}
}
public class XYZ : ABC
{
public XYZ(int x):base(2)
{
Console.WriteLine("Constructor XYZ");
}
public void show(P p)
{
Console.WriteLine("From XYZ");
}
}
class Program
{
static void Main(string[] args)
{
XYZ b = new XYZ(1);
b.show(new Q());
Console.ReadLine();
}
output: Constructor ABC
Constructor XYZ
From XYZ
============================
1. Hello world -> how many times all chars
2.Delete Duplicate chars from line
https://dotnettutorials.net/lesson/how-to-remove-duplicate-characters-from-a-string-in-chsrap/
3. Remove 1st and Last/nth char String
2. Extension method implement
3. Duplicate char finding from string
4. Sorting bubble (LINQ ->
5. Array from Dublipcate number
6. Reverse string/palindrome
7. Nunit Test case Visual studio API
8. Readonly in the declaration and only can assign in constructor only , example : injectionDi
9.Memory leak c#
10. stack n Heap memory management c#
11.Access modifier (public private internal , others combinations)
12. Collections , dictionary , dictionary to array conversion
https://www.techiedelight.com/convert-dictionary-values-to-an-array-in-csharp/
13. lemda expressions n func n actions
14. bubble sort -> complexity
14. Tupple when use tupple
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/value-tuples
15 display * as triangle
https://eddiejackson.net/wp/?p=21062
16
9. leftjoin Linq
var QSOuterJoin = from emp in Employee.GetAllEmployees()
join add in Address.GetAddress()
on emp.AddressId equals add.ID
into EmployeeAddressGroup
from address in EmployeeAddressGroup.DefaultIfEmpty()
select new {emp, address };
10. RightJoin Linq :
//Defered Query Execution
var rightJoin = from skill in skills
join deve in developers
on skill.Id equals deve.SkillID into joinDeptEmp
from employee in joinDeptEmp.DefaultIfEmpty()
select new {
EmployeeName = employee != null ? employee.Name : null,
SkillName = skill.Name
};
11.The basic difference between a Deferred execution vs Immediate execution
is that Deferred execution of queries produce a sequence of values,
whereas Immediate execution of queries return a singleton value and is executed immediately.
Examples are using Count(), Average(), Max() etc.
The basic difference between a Deferred execution vs Immediate execution
https://www.dotnetcurry.com/linq/750/deferred-vs-immediate-query-execution-linq#:~:text=The%20basic%20difference%20between%20a,Average()%2C%20Max()%20etc.
pelingrom
12.
Revser of line
using System;
public class HelloWorld
{
public static void Main(string[] args)
{
var inPutString = Console.ReadLine ();
var reveseStriing = "";
foreach(var item in inPutString.Split())
{
// item.Reverse()
// char[] charArray = item.ToCharArray();
//Array.Reverse(charArray);
// Console.WriteLine(new string(charArray));
// reveseStriing +=" " +new string(charArray);
reveseStriing +=" " +RevserCustom(item);
}
Console.WriteLine (reveseStriing.Trim());
// Console.WriteLine (inPutString);
}
public static string RevserCustom(string inputString)
{
var charrArray = inputString.ToCharArray();
var length = charrArray.Length;
var reverseArray = new char[charrArray.Length];
for(int i=0;i < length ; i++)
{
reverseArray[length-i-1] = charrArray[i];
}
// Console.WriteLine (new string(reverseArray));
return new string(reverseArray);
}
}
Q2. PelineDrome
// Online C# Editor for free
// Write, Edit and Run your C# code using C# Online Compiler
using System;
public class HelloWorld
{
public static void Main(string[] args)
{
var inPutString = Console.ReadLine();
var charArray = inPutString.ToCharArray();
var ispalindrome = true;
for(int i=0 ;i<charArray.Length ; i++ )
{
if(charArray[i]!=charArray[charArray.Length-i-1])
{
ispalindrome = false;
break;
}
continue;
}
if(ispalindrome)
Console.WriteLine ("Pelindrom");
else
Console.WriteLine ("Not Palindrome");
}
}
Q3 : Reverse
Reverse String
// Online C# Editor for free
// Write, Edit and Run your C# code using C# Online Compiler
using System;
public class HelloWorld
{
public static void Main(string[] args)
{
var inPutString = Console.ReadLine();
var charArray = inPutString.ToCharArray();
var ispalindrome = true;
var length = charArray.Length;
var reverseCharArray = new char[length];
for(int i=0 ;i<length ; i++ )
{
if(charArray[i]!=charArray[length-i-1])
{
ispalindrome = false;
break;
}
reverseCharArray[i] = charArray[length-i-1];
continue;
}
if(ispalindrome)
{
Console.WriteLine("Pelindrom and Reseverse string is " +
new string(reverseCharArray));
}
else
Console.WriteLine ("Not Palindrome");
}
}
------------------------Reverse array and show with spaces
using System;
namespace HelloWorld
{
class Program
{
static void Main(string[] args)
{
char[] charArray = new char[] { 'a', 'b', 'c' };
char[] reverseArray = new char[charArray.Length] ;
for (int i = 0; i < charArray.Length; i++)
{
//reverseArray[charArray.Length-i-1] = charArray[i];
var result = new string('\t', i)+ charArray[charArray.Length-i-1] ;
Console.WriteLine(result);
}
Console.ReadKey();
}
}
}
---------------------------------------
How to Implement Bubble Sort in C#?
We are going to define an integer array property NumArray, that we are going to use to implement the bubble sort algorithm:
Let’s create a method that implements the bubble sort algorithm in C# that sorts the values in the NumArray property:
Time and Space Complexity
The space complexity of the bubble sort algorithm is O(1) because it requires a single additional space that holds the temporary value we are using to swap the elements.
Nested loops have detrimental effects on how algorithms perform as the size of the array grows. The bubble sort algorithm has a time complexity of O(N²) as it has two nested loops. Let’s analyze how the algorithm performs in different levels of complexity.
Q.---------CIRCLE with *
using System;
class Program
{
static void Main()
{
int radius = 5; // Radius of the circle
int centerX = 10; // X-coordinate of the circle's center
int centerY = 10; // Y-coordinate of the circle's center
DrawCircle(radius, centerX, centerY);
}
static void DrawCircle(int radius, int centerX, int centerY)
{
int diameter = radius * 2;
for (int y = 0; y <= diameter; y++)
{
for (int x = 0; x <= diameter; x++)
{
int distanceX = Math.Abs(x - radius);
int distanceY = Math.Abs(y - radius);
double distance = Math.Sqrt(distanceX * distanceX + distanceY * distanceY);
if (distance > radius - 0.5 && distance < radius + 0.5)
{
Console.Write("*");
}
else
{
Console.Write(" ");
}
}
Console.WriteLine();
}
}
}
No comments:
Post a Comment