LINQ Basic Selects

Whether a select is required or not


' Notice no select is required
Dim fileStringCollection = From anythingGoesHere _
                           In My.Computer.FileSystem.GetFiles("C:\")


// Select is required
var fileStringCollection = from anythingGoesHere
                           in Directory.GetFiles(@"C:\")
                           select anythingGoesHere;

Selecting into an object / properties


Dim objCollection = From objs _
                    In fileStringCollection _
                    Select New WrapperForStrings _
                      With {.StringProperty = objs}


var objCollection = from objs
                    in fileStringCollection
                    select new WrapperForStrings
                      {StringProperty = objs};

Returning multiple columns (via an instance of an anonymous class) in a select


' VB can just use a plain syntax as follows
Dim myInfoCollection = From file In filesInfoCollection _
                       Select file.Name, file.CreationTime


// In C# you must explicitly create a new (anonymous) object and explicitly define the properties and values
var myInfoCollection = from file in filesInfoCollection
                       select new { CSName = file.Name,
                         CSCreationTime = file.CreationTime };

Edit: For an example of WrapperForStrings see this post


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s