Since I have Orcas installed, one of the first things I decided to experiement with is LINQ. 2.0 adds great support for generic collections, but often I find looking for a particular item in one a total pain in the ass. Traditionally, your only options are to iterate over each item or use an anonymous method or something. Thanks to LINQ, this is now an easy task.
Let's start by looking at this simple class below.
public class MyClass
{
private int myInt;
private string myString;
public int MyInt
{
get { return myInt; }
set { myInt = value; }
}
public string MyString
{
get { return myString; }
set { myString = value; }
}
}
Then we'll add a few instances of this class to a generic collection.
List myList = new List();
myList.Add(new MyClass { MyInt = 1, MyString = "Blah 1" });
myList.Add(new MyClass { MyInt = 2, MyString = "Blah 2" });
myList.Add(new MyClass { MyInt = 3, MyString = "Blah 3" });
myList.Add(new MyClass { MyInt = 4, MyString = "Blah 4" });
Notice the use of the new object intiializer on the MyClass instantiation. So say you want to return all items where the value of MyInt is greater than or equal to 3. Before LINQ, you would probably be iterating manually through and emitting the contents into another list or who knows. Now, you can simply query it.
var = from myClass in myList
where myClass.MyInt > 2
select myClass;
Going line by line here. The first statement says where to get the data from, in this case the generic list myList. The value myClass is effectively an iterator and can be named anything (i.e.: i). The second line applies a where clause. MyInt (along with all other public properties) will be available for selection in IntelliSense through the use of reflection. The last line, tells it what to return. In this case, it returns the whole class. This could also be individual properties (i.e.: myClass.MyInt, myClass.MyString). In this case I am letting the return type be set implicilty using var. In reality the actual return type if IEnumerable.
Once you get the data queried, its easy to bind it to a grid or anything else.
GridView2.DataSource = neat2;
GridView2.DataBind();
Obviously this makes things easy. LINQ works on your own collections as well as directly against a database using LINQ to SQL. Is this necessarily the correct way to do things? Does it perform well? Will using LINQ deem you as a Cowboy Coder? Only time will tell.
Read the complete post at http://www.dotnettipoftheday.com/blog.aspx?id=362