Pages

Sunday, June 1, 2014

Easy Linq Example



Linq is a great tool to introduce the power of SQL to the C# environment.  I have found lots of uses for Linq, but this is just a quick sample to get you started.


 //Create a list of random integers
            List<int> myList = new List<int>();
            Random random = new Random();
            for (int i = 0; i < 1000; i++)
            {
                myList.Add(random.Next(0, 500));
            }

            //list is loaded
            //find the values > 10, eliminate dups, and sort.
            //now watch Linq in action

            List<int> filteredList = myList
                .Where<int>(r => r > 10)
                .Distinct()
                .OrderBy(r => (int)r).ToList();

            int fullList = myList.Count();
            int distinctList = filteredList.Count();

            //pop up the counts
            MessageBox.Show(string.Format("{0} records, {1} unique values.", fullList, distinctList));

            //pop up the list
            MessageBox.Show(string.Join(", ",filteredList.ToList()));







...

Bryan Valencia is a contributing editor and founder of Visual Studio Journey.  He owns and operates Software Services, a web design and hosting company in Manteca, California.

Share This!

Contact Us

Name

Email *

Message *