Printed from A Developer website designed for Developers

LINQ to Objects


The term "LINQ to Objects" refers to the use of LINQ queries with any IEnumerable or IEnumerable collection directly, without the use of an intermediate LINQ provider or API. You can use LINQ to query any enumerable collections such as List, Array, or Dictionary.

LINQ to Objects provides methods that represent a set of standard query operators to retrieve data from any object whose class implements the IEnumerable interface. These queries are performed against in-memory data.

Code Example

For more advanced code example, see LINQ to objects code review.

class Person { public Int32 ID { get; set; } public Int32 IDRole { get; set; } public String LastName { get; set; } public String FirstName { get; set; } }
class Program { static void Main(string[] args) { List<Person> people = new List<Person> { new Person() {ID = 1, IDRole = 1, LastName = "Anderson", FirstName = "Brad"}, new Person() {ID = 2, IDRole = 2, LastName = "Gray", FirstName = "Tom"} };
var query = from p in people where p.ID == 1 select new { p.FirstName, p.LastName };
foreach (var element in query) { Console.WriteLine("Anonymous Type: First Name = {0}, Last Name = {1}", element.FirstName, element.LastName); } Console.WriteLine();
var query2 = from Person p in people where p.ID == 1 select p;
foreach (Person p in query2) { Console.WriteLine("Person Type: First Name = {0}, Last Name = {1}", p.FirstName, p.LastName); } Console.Read(); } }