Sunday, May 22, 2022

C# System.Collections.Generic

 1) ToLookup()

  1. It creates a Key based on the user's choice at runtime. In this article I have used the length of the string as the Key. So it stores data and creates the key based on the length of the string.
    E.g. "Lajapathy" has a length of 9, so the key is created with the value 9 and the value is "Lajapathy".
  2. Exactly the same concept of Dictionary<K, T>, but the key is not static; it is dynamic.
  3. Setting key at Runtime.
  4. It is very useful if using complex data type.
  5. It is useful to get data fast, because it stores as Index key.
  6. It is a KeyValue<K, T> pair.

Example

public static List<string> GetStringList()
    {
        List<string> list = new List<string>();
        list.Add("Lajapathy");
        list.Add("Sathiya");
        list.Add("Parthiban");
        list.Add("AnandBabu");
        list.Add("Sangita");
        list.Add("Lakshmi");
        return list;
    }

.................................
.................................

        List<string> list = GetStringList();
 
        //Sets KeyValue pair based on the string length.
        ILookup<intstring> lookup = list.ToLookup(i => i.Length);


        //Iterates only string length having 7.
        foreach (string temp in lookup[7])
        {
            HttpContext.Current.Response.Write(temp + "<br/>");
        }

======================================================

    public static List<Employee> EmployeeList()
    {
        List<Employee> emp = new List<Employee>();
        emp.Add(new Employee { ID = 100, Name = "Lajapathy", CompanyName = "FE" });
        emp.Add(new Employee { ID = 200, Name = "Parthiban", CompanyName = "FE" });
        emp.Add(new Employee { ID = 400, Name = "Sathiya", CompanyName = "FE" });
        emp.Add(new Employee { ID = 300, Name = "Anand Babu", CompanyName = "FE" });
        emp.Add(new Employee { ID = 300, Name = "Naveen", CompanyName = "HCL" });
        return emp;
    }
..............................................
..............................................
        List<Employee> empList = EmployeeList();
        //Creating KeyValue pair based on the ID. we can get items based on the ID.
        ILookup<intEmployee> lookList = empList.ToLookup(id => id.ID); 

        //Displaying who having the ID=100.
        foreach (Employee temp in lookList[100])
        {
            Console.WriteLine(temp.Name);
        } 

========================================================

2) Max, Min methods

using System.Linq;
using System.Collections.Generic;
................

List<int> list = new List<int>() { 5, -1, 4, 9, -7, 8 };

int maxValue = list.Max();
int maxIndex = list.IndexOf(maxValue);
 
int minValue = list.Min();
int minIndex = list.IndexOf(minValue);
 
Console.WriteLine("Maximum element {0} present at index {1}", maxValue, maxIndex);
Console.WriteLine("Minimum element {0} present at index {1}", minValue, minIndex);



3) Where , FirstOrDefault


        List<string> myList = new List<string>();
        list.Add("Lajapathy");
        list.Add("Sathiya");
        list.Add("Parthiban");
        list.Add("AnandBabu");
        list.Add("Sangita");
        list.Add("Lakshmi");


       //return the first item which matches your criteria or Null
      string result = myList.FirstOrDefault(s => s == "Lakshmi");


      //return all items which match your criteria
     IEnumerable<string> results = myList.Where(s => s == search);



4) LIKE operator in LINQ


Typically you use String.StartsWith/EndsWith/Contains. For example:


public class Student{
public int Id;
public string Name;
}

var students= new List<Student>() { 
                new Student(){ Id = 1, Name="Bill"},
                new Student(){ Id = 2, Name="Steve"},
                new Student(){ Id = 3, Name="Ram"},
                new Student(){ Id = 4, Name="Abdul"}
            };

var id = students
                       .Where(p => p.Name.Contains("u"))
                       .FirstOrDefault()
                       .Id;


5) AddRange to Append to List


var favouriteCities = new List<string>();
var popularCities = new List<string>();

string[] cities = new string[3]{ "Mumbai", "London", "New York" };

popularCities.AddRange(cities);
favouriteCities.AddRange(popularCities);


6) Remove vs RemoveAt


var numbers = new List<int>(){ 10, 20, 30, 40, 10 };

numbers.Remove(10); // removes the first 10 from a list

numbers.RemoveAt(2); //removes the 3rd element (index starts from 0)



7) Contains() to Check Elements in List


var numbers = new List<int>(){ 10, 20, 30, 40 };
numbers.Contains(10); // returns true
numbers.Contains(11); // returns false



8) Sort vs Reverse()


var words = new List<string> {"falcon", "order", "war", "sky", "ocean", "blue", "cloud", "boy"};

words.Sort();
Console.WriteLine(string.Join(",", words));

words.Reverse();     // descending order
Console.WriteLine(string.Join(",", words));



9) Linq OrderBy()


class Pet { public string Name { get; set; } public int Age { get; set; } } public static void OrderByEx1() { Pet[] pets = { new Pet { Name="Barley", Age=8 }, new Pet { Name="Boots", Age=4 }, new Pet { Name="Whiskers", Age=1 } }; IEnumerable<Pet> query = pets.OrderBy(pet => pet.Age); foreach (Pet pet in query) { Console.WriteLine("{0} - {1}", pet.Name, pet.Age); } } /* This code produces the following output: Whiskers - 1 Boots - 4 Barley - 8 */


10)  Linq: from where select



// Specify the data source. int[] scores = { 97, 92, 81, 60 }; // Define the query expression. IEnumerable<int> scoreQuery = from score in scores where score > 80 select score; // Execute the query. foreach (int i in scoreQuery) { Console.Write(i + " "); } // Output: 97 92 81



11) Linq Distinct, OrderBy 


string s = "efgabcddddddaaaaaaaaaaa";
List<char> myList = s.Distinct().OrderBy(q => q).ToList();
Console.Write(string.Join(">",myList));    //a>b>c>d>e>f>g