String Writer

my tech stuffs…

Archive for the ‘LINQ’ Category

LINQ : Looping through ArrayList/List

with one comment

In C#, we generally use for/foreach/while to loop through an array or any collection object. Now LINQ is providing an easy way of navigating through a collection. I use this for simple condition checking J


List<Employee> employees = new List<Employee>();

employees.Add(new Employee("E001", "Bala", 10000));
employees.Add(new Employee("E002", "Arun", 15000));
employees.Add(new Employee("E003", "Ashok", 20000));
employees.Add(new Employee("E004", "Thiru", 25000));
employees.Add(new Employee("E005", "Ugi", 10600));
employees.Add(new Employee("E006", "VRS", 11000));
employees.Add(new Employee("E007", "Naren", 11200));

var emps = employees.Where((emp, index) => emp.Salary >= 20000);

foreach (var e in emps)
{
  Console.WriteLine(e.Name);
}

 

LINQ provides an extension method, Where which will fetch each item in emp object with index of an collection.

 

var emps = employees.Where((emp, index) => emp.Salary >= 20000);

You don’t need to declare emp and index variables. For more details, you need to look into predicate feature in LINQ.

This can also be done in LINQ without using extension method which is more like SQL statements.

 

var emps = from emp in employees
 where emp.Salary >= 15000
  select emp;


Below is the traditional way of looping which is really boring and thank god I got something to try new.

foreach (Employee e in employees)
{
 if(e.Salary >= 15000)
  Console.WriteLine(e.Name);
}

Written by visvabalaji

January 24, 2007 at 12:29 am

Posted in C#, LINQ

Tagged with ,

LINQ : OfType<T>()

leave a comment »

OfType<T> : Another useful and commonly used extension methods in LINQ. Assume that you have an array or collection of values which is of multiple types and you are required to filter only the values of specific type.


public void Process(List<Account> accounts)
{
  Console.WriteLine("Available Credit Cards :");

  foreach (var cc in accounts.OfType<CreditCardAccount>())
  {
    Console.WriteLine(cc.Name);
  }

  Console.WriteLine("Available Savings Accounts :");

  foreach (var sb in accounts.OfType<SavingsAccount>())
  {
    Console.WriteLine(sb.Name);
  }
}

Here’s the output of this method.

clip_image001

Written by visvabalaji

January 17, 2007 at 5:58 am

Posted in C#, LINQ

Tagged with , ,

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: