Source Code



C# LINQ

  • Fandi Susanto
  • 21 November 2013 at 09:31
  • C Sharp
  • 282
  • 81
  • United States
 


Author: Fandi Susanto Language: United States
License: Freeware
Size: 0 KB
Downloads: 19 times

 

LINQ (Language-Integrated Query) in C# is a simple way to query and update a Collection of data. We can use LINQ for example to filter, sort or even merge data in collections. The simplest way to use LINQ is:


from [itemIdentifier] in [collection] where [condition] select [itemIdentifier]


Below are examples of LINQ usage:


class Program {
  static void Main(string[] args) {
    List<Student> Students = new List<Student>() {
      new Student(Fandi, Physics, 2001),
      new Student(Agung, Physics, 2001),
      new Student(Jon, Physics, 2000),
      new Student(Arthur, Physics, 2000),
      new Student(Hendera, Chemistry, 2001),
      new Student(Kurniawan, Chemistry, 2001),
    };
 
    Console.WriteLine(Year 2001 Students:);
    IEnumerable<Student> year2001 = from s in Students where s.AdmittanceYear == 2001 select s;
    foreach (Student s in year2001) {
      Console.WriteLine(s);
    }
 
    Console.WriteLine(nPhysics students:);
    List<Student> physics = (from s in Students where s.Major == Physics select s).ToList();
    foreach (Student s in physics) {
      Console.WriteLine(s);
    }
 
    Console.WriteLine(nPhysics students year 2001:);
    IEnumerable<string> physics2001 = from s in Students where s.Major == Physics && s.AdmittanceYear == 2001 select s.Name;
    foreach (string s in physics2001) {
      Console.WriteLine(s);
    }
 
    Console.ReadKey();
  }
}


For that example, we need a Student class:

class Student {
  public string Name { get; set; }
  public string Major { get; set; }
  public int AdmittanceYear { get; set; }
  public Student(string name, string major, int year) {
    this.Name = name;
    this.Major = major;
    this.AdmittanceYear = year;
  }
  public override string ToString() {
    return Name : + Name
      + nMajor: + Major
      + nYear : + AdmittanceYear
      + n--------------------;
  }
}


LINQ return value is an IEnumerable. IEnumerable is a form of collection which is best be used with foreach loops, in forward only reading. But it can also be converted to List as seen on the second LINQ example above. The third example, shows that LINQ can also retrieve a single member of the objects. For more advanced techniques on LINQ, visit the MSDN.
comments powered by Disqus

Related Code

Allow Single URL Through .htaccess Password Protection

Countable is a JavaScript function

Passing JavaScript variables to PHP

Create Dynamic Bar Graph or Chart in php

Securimage with Image

INFORMATION_SCHEMA.TABLES

A Simple PHP Image Resize Code

How Create a Zip File Using PHP

Icon Extractor - full delphi source code

Func-In Delphi Example



Category

Tag Linked