What's new in VS2008? Querying objects with LINQ adds real power to the developer's arsenal of tools for code production.
The most time consuming part of any application is usually developing code that manipulates data. If you thought about "manipulating data" before the advent of Visual Studio .NET, you prrobably thought of data from database or files. With the coming of .NET, data moved to Objects and manipulation of data began to include Objects, Arrays, ArrayLists, Collections, XML, etc.
With the release of VS 2008 comes a whole new paradigm of development tools. One of the sweetest is LINQ. Data can be encapsulated in all of the previous containers and forms, but LINQ gives us power in extracting and manipulating data in these containers. Obviously, we had multiple ways to find and manipulate data for all of the aforementioned objects and forms prior to the advent of LINQ. However, LINQ is an attempt to give developers a consistent methodology for manipulating internal data that is much like SQL is used to manipulate database data.
In this article, I will create a simple application of LINQ to whet your appetite. I will create a Console Application. Sub Main is shown below. It creates an array of names and calls two methods; one pulling data from an array in the convention way and the second using LINQ. Click here to see the VB.NET Version.
| public void Main() { string[] names = {"Smith", "Jones", "Samson", "Doe", "Sanders", "Frank"}; QueryArrayTheOldWay(names); Console.WriteLine(" "); LinqQueryStrings(names); } |
| private void QueryArrayTheOldWay(string[] names) { ArrayList sList = new ArrayList(); // create an arraylist of names beginning with "S" Console.WriteLine("Do it the old way"); foreach (string s in names) { if (s.Substring(0, 1).Equals("S")) sList.Add(s); } for (int i = 0; i < sList.Count - 1; i++)<BR> { Console.WriteLine("Name {0} beginning with S: " + sList[i], System.Convert.ToString(i + 1)); } } |
| private void LinqQueryStrings(string[] names) { // create an arraylist of names beginning with "S" IEnumerable<string> sList = From s In names Where s.Substring(0, 1).Equals("S"); // print the subset of names int tempFor1 = sList.Count; for (int i = 0; i < tempFor1; i++)<BR> { Console.WriteLine("Name {0} beginning with S: " + sList(i), System.Convert.ToString(i + 1)); } Console.ReadLine(); } |

| Ask a Question, or give your feedback on my articles or products by going to the KnowDotNet Forum or by clicking on My Blog. | ![]() |