Aidan Garnish

Collaboration Not Competition

Some simple Linq to Objects examples

Linq to Objects is a really handy way to filter and order lists of objects. The following code is a simple example that shows how to filter and how to order a list by an object property.

//a little bit of object and list set up
            ContractPerson person1 = new ContractPerson()
            {   Name = "Aidan Garnish",
                AccountID = "1",
                Company = "65hours",
                Email = "aidan@65hours.com",
                Role = "SharePoint Consultant" };

            ContractPerson person2 = new ContractPerson()
            {
                Name = "Fred Smith",
                AccountID = "2",
                Company = "65hours",
                Email = "fred@65hours.com",
                Role = "Dynamics Consultant"
            };

            ContractPerson person3 = new ContractPerson()
            {
                Name = "Joe Blogs",
                AccountID = "3",
                Company = "Microsoft",
                Email = "joe@ms.com",
                Role = "Microsoft Consultant"
            };

            List<ContractPerson> people = new List<ContractPerson>();
            people.Add(person1);
            people.Add(person2);
            people.Add(person3);


            //filter list by ContractPerson.Company
            var filteredPeople = from person in people
                        where person.Company == "65hours"
                        select person;
           
            foreach (ContractPerson filterPerson in filteredPeople)
            {
                Console.WriteLine(filterPerson.Name);
            }

            //filter list by people who have a name beginning with A
            var peopleWithNameStartingA = from person in people
                                 where person.Name.StartsWith("A")
                                 select person;

            foreach (ContractPerson filterPerson in peopleWithNameStartingA)
            {
                Console.WriteLine(filterPerson.Name);
            }

            //order the list
            var orderedList = from person in people
                              orderby person.Name ascending
                              select person;

            foreach (ContractPerson orderedPerson in orderedList)
            {
                Console.WriteLine(orderedPerson.Name);
            }

            Console.ReadLine();

Add comment

Loading