Linq Coding Practice
Linq Question
Concept with exapmle
using System;
using System.Collections.Generic;
using System.Linq;
public class Program
{
public static void Main()
{
// Linq question
List<int> num = new List<int>() {1,2,4,5,6,7,2,6};
//Q1- distinct numbers form the list using LINQ
IEnumerable<int> unqNum = num.Distinct().ToList();
foreach(var n in unqNum){
Console.Write(n + " ");
}
Console.WriteLine();
// filtering
// Q2- find Even & odd numbers from list
IEnumerable<int> evenNum = num.Where(n => n%2==0).ToList();
IEnumerable<int> oddNum = num.Where(n => n%2!=0).ToList();
Console.Write("Even numbers: ");
foreach(var n in evenNum){
Console.Write(n + " ,");
}
Console.WriteLine();
Console.Write("odd numbers: ");
foreach(var n in oddNum){
Console.Write(n + ", ");
}
Console.WriteLine();
// sorting
// Assending order
IEnumerable<int> ascNum = num.OrderBy(x=> x).ToList();
Console.Write("Assinding order: ");
foreach(var n in ascNum){
Console.Write(n + " ");
}
Console.WriteLine();
// dessinding order
IEnumerable<int> descNum = num.OrderByDescending(x=>x).ToList();
Console.Write("dessinding order: ");
foreach(var n in descNum){
Console.Write(n + " ");
}
Console.WriteLine();
// first() and firstOrDefault()
var first = num.First();
Console.WriteLine("first: "+ first);
var EmptyList = new List<int>() {};
//var firstEmpty = EmptyList.First(); // InvalidOperationException - Sequence contain no elements
//Console.WriteLine("first: "+ firstEmpty);
var firstEmpty_ = EmptyList.FirstOrDefault(); // similar LastOrDefault();
Console.WriteLine("first: "+ firstEmpty_);
// Any() - any number satisfy the condition return true or false
// All() - all number satisfy the condition return true or false
var secList = new List<int>() {3,5,7};
var checkEven = num.Any(x=> x%2==0); // return true
var checkEvenInSecList = secList.Any(x=> x%2==0); // return false
Console.WriteLine("is Even num in numList: {0}, is Even num in secList: {1}",checkEven,checkEvenInSecList);
// Skip() & Take()
//first 3 Element
var fistThree = num.Take(3).ToList();
foreach(var n in fistThree){
Console.Write(n + " ");
}
Console.WriteLine();
// skip first 2 element from list
var skipFirst2 = num.Skip(2).ToList();
foreach(var n in skipFirst2){
Console.Write(n + " ");
}
Console.WriteLine();
// Zip - merge element at crospondind position
var numbers = new List<int>() {1,2,3};
var latters = new List<char>() {'a','b','c'};
var res = numbers.Zip(latters, (num, latter) => $"{num}-{latter}");
foreach(var n in res){
Console.Write(n + " "); // give result 1-a 2-b 3-c
}
Console.WriteLine();
//aggragate function
var intList = new List<int>() {1,2,3,4,5};
//M-1: Built-in aggragate fun
//Sum: int total = num.Sum();
//Average: double avg = num.Average();
//Min / Max: int smallest = num.Min(); / int largest = num.Max();
//Count: int totalItems = num.Count();
int total = intList.Sum();
Console.WriteLine("Total :"+ total);
//M-2: The Custom .Aggregate() Method
//This method works by keeping track of an accumulator value as it moves through the list.
int totalInt = intList.Aggregate((acc, next) => acc + next);
Console.WriteLine("Total :"+ totalInt);
//Practical Example: Building a String
//You can also use it to format your output—like turning your list into a comma-separated string:
string intListFormate = intList
.Select(x=> x.ToString())
.Aggregate((acc,next) => acc + ", "+ next);
Console.WriteLine("String Formate :"+ intListFormate);
}
}
OutPUT:
1 2 4 5 6 7
Even numbers: 2 ,4 ,6 ,2 ,6 ,
odd numbers: 1, 5, 7,
Assinding order: 1 2 2 4 5 6 6 7
dessinding order: 7 6 6 5 4 2 2 1
first: 1
first: 0
is Even num in numList: True, is Even num in secList: False
1 2 4
4 5 6 7 2 6
1-a 2-b 3-c
Total :15
Total :15
String Formate :1, 2, 3, 4, 5
SelectMany
using System;
using System.Collections.Generic;
using System.Linq;
public class Program
{
public static void Main()
{
// Select many
var order = new List<Order>()
{
new Order {Id=1, Product= new List<string> {"P1","P2"}},
new Order { Id= 2, Product= new List<string> {"P2","P3"}}
};
Console.Write(" ");
var allproduct = order.SelectMany(order=> order.Product).Distinct().ToList();
foreach(var item in allproduct){
Console.Write( item +" "); // output: P1 P2 P3
}
}
}
public class Order{
public int Id {get; set;}
public List<string> Product {get; set;}
}
JOIN
using System;
using System.Collections.Generic;
using System.Linq;
public class Program
{
public static void Main()
{
var customers = new List<Customer>
{
new Customer {Id =1, Name = "SKS"},
new Customer {Id =2, Name = "ACS"}
};
var orders = new List<Order>
{
new Order { CustId=1, Amount= 300.00},
new Order { CustId=2, Amount= 400.00}
};
// Join
var customerOrder = customers.Join(
orders,
customer => customer.Id, // Key from Customers
order => order.CustId, // Key from Orders
(customer, order) => new
{
CustomerName = customer.Name,
OrderAmount = order.Amount
});
foreach(var co in customerOrder)
{
Console.WriteLine($"{co.CustomerName}- {co.OrderAmount}");
}
}
}
public class Customer{
public int Id {get; set;}
public string Name {get; set;}
}
public class Order{
public int CustId {get;set;}
public double Amount {get;set;}
}
// OUTPUT : SKS- 300 ACS- 400
Comments
Post a Comment