Element Operators

First - Simple

This sample uses First to return the first matching element as a Product, instead of as a sequence containing a Product.

Code:

            public void Linq58()
            {
                List products = GetProductList();

                Product product12 = (products.Where(prod => prod.ProductID == 12)).First();

                ObjectDumper.Write(product12);
            }

Result:

First - Condition

This sample uses First to find the first element in the array that starts with 'o'.

Code:

            public void Linq59()
            {
                string[] strings = { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" };

                string startsWithO = strings.First(s => s[0] == 'o');

                Log.WriteLine("A string starting with 'o': {0}", startsWithO);
            }

Result:

FirstOrDefault - Simple

This sample uses FirstOrDefault to try to return the first element of the sequence, unless there are no elements, in which case the default value for that type is returned. FirstOrDefault is useful for creating outer joins.

Code:

            public void Linq61()
            {
                int[] numbers = { };

                int firstNumOrDefault = numbers.FirstOrDefault();

                Log.WriteLine(firstNumOrDefault);
            }

Result:

FirstOrDefault - Condition

This sample uses FirstOrDefault to return the first product whose ProductID is 789 as a single Product object, unless there is no match, in which case null is returned.

Code:

            public void Linq62()
            {
                List products = GetProductList();

                Product product789 = products.FirstOrDefault(p => p.ProductID == 789);

                Log.WriteLine("Product 789 exists: {0}", product789 != null);
            }

Result:

ElementAt

This sample uses ElementAt to retrieve the second number greater than 5 from an array.

Code:

            public void Linq64()
            {
                int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };

                int fourthLowNum = (numbers.Where(num => num > 5)).ElementAt(1);  // second number is index 1 because sequences use 0-based indexing

                Log.WriteLine("Second number > 5: {0}", fourthLowNum);
            }

Result: