Home  • Programming • C#.NET

Example of LINQ to List<T>

You can use LINQ to query against data stored in a collection class, such as the List<T> class (among many others). The following code creates a new List<Employee> collection. The Employee class is simply a custom class that was written to hold a few properties. The code then defines a simple LINQ query against the class. You can then iterate over the collection defined by the query.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Lesson_linq_to_list
{
    class Program
    {
        static void Main(string[] args)
        {
            List<Employee> employees = new List<Employee>();
            Employee emp1 = new Employee("10", "Iqbal", "Dhaka", "IT");
            employees.Add(emp1);
            employees.Add(new Employee("11","Samrat","Mirpur","FI"));
            employees.Add(new Employee("12","Jahir","Dhanmondi","AD"));
            employees.Add(new Employee("13","Minhaz","Rampura","AC"));

            IEnumerable<Employee> empQuery = from emp in employees
                                             where emp.First.Length > 5
                                             select emp;


            foreach (Employee emp in empQuery) {

                Console.WriteLine(emp.First);
            
            }

            Console.ReadKey();

        }
    }

    class Employee
    {
        public string ID { set; get; }
        public string First { set; get; }
        public string City { set; get; }
        public string Department { set; get; }

        public Employee() { }
        public Employee(string _id, string _first, string _city, string _dept)
        {
            this.ID = _id;
            this.First = _first;
            this.City = _city;
            this.Department = _dept;
        }
    }
}

Comments 0


Share

Copyright © 2024. Powered by Intellect Software Ltd