C# features – LINQ primer

April 30, 2009 | by Geoff

Language INtegrated Query (LINQ) adds extensions to the .NET framework which provide a domain specific language for querying and transforming collections right within C# (or VB for that matter). It provides syntax similar to other 4GL querying languages such as SQL, HQL or even OQL.

Below is a simple test case showing how to do LINQ operations on a simple array:

        public void LinqArrayTest()
        {
            String[] names = { "Burke", "Connor", "Frank",
                   "Everett", "Albert", "George",
                   "Harris", "David" };

            IEnumerable<string> query = from s in names
                               where s.Length == 5
                               orderby s
                               select s;

            List<String> results = query.ToList();

            Assert.AreEqual(3, results.Count);
            String[] expected = new String[] {"Burke", "David", "Frank"};
            for (int i = 0; i < results.Count; i++)
            {
                Assert.AreEqual(expected[i], results.ElementAt(i));
            }
        }

It is also possible to create runtime LINQ queries using lambda expressions to qualify conditional logic:

        [TestMethod()]
        public void LinqLambdaTest()
        {
            String[] items = { "cabbage", "broccoli", "carrot", "parsnip", "cauliflower" };

            IEnumerable<String> query = items;

            // additive query generation using lambda expressions
            query = query.Where(item => item.StartsWith("c"));
            query = query.Where(item => item.Length < 8);
            query = query.OrderByDescending(item => item.ToLower());

            List<String> results = query.ToList();

            Assert.AreEqual(2, results.Count);
            String[] expected = { "carrot", "cabbage" };
            for (int i = 0; i < results.Count; i++)
            {
                Assert.AreEqual(expected[i], results.ElementAt(i));
            }
        }

LINQ provides a simple, generalised query framework for operating on data collections within the .NET stack. There are framework plugins to support LINQ backed by various datastore technologies, these include: LINQ to SQL, LINQ to XML and LINQ to Entities.

Bookmark and Share

Tags: , ,

One Response to “C# features – LINQ primer”

  1. Behringer Says:

    Very nice , thanks ..

Leave a Reply