My LINQ Cheatsheet#

I've been banging .NET 3.5 lately and this rendezvouz with LINQ (Language Integrated Query) has been making my brain smile alot. I mean, how can you not like something so easy and well defined and makes your life as developer alot easier.

Anyhow, I just wanted to post my LINQ cheat sheet. It's not much and it's not even complete yet (I call this part 1.1). It consist of a few snippets that you might commonly do when doing LINQ processing. I'm planning to update this and hopefully I could find time this week to add some more piece of code that would demonstrate the other LINQ topics that I missed.

Anyway, here's some LINQ snippets:

//create our PersonService object
PersonService ps = new PersonService();

//get the list of person
PersonList listOfPerson = ps.GetPersonList();

//get a list of people with Gender set to Male
var maleOnlyList =
from l
in listOfPerson
where l.Gender == Gender.Male
select l;

//get a list of people with Gender set to female
//and declaring the returned fields
var femaleOnlyList =
from l
in listOfPerson
where l.Gender == Gender.Female
select new {
l.PersonID,
l.FirstName,
l.MiddleName,
l.LastName,
l.Email,
l.BirthDate,
l.Gender,
l.DateCreated };

//specify age
int selectedAge = 25;
//get a list of people with age greater than 25
var ageIsGreaterThan25 =
from l
in listOfPerson
where l.BirthDate >= DateTime.Now.AddYears(-selectedAge)
select l;

//get a list of people with a birthdate between a specified range
var birthdateBetweenRange =
from l
in listOfPerson
where
l.BirthDate >= DateTime.Parse("1/1/1980")
&& l.BirthDate <= DateTime.Parse("1/1/1981")
select l;


//order the result by lastname
var orderByLastNameSimple =
from l
in listOfPerson
orderby l.LastName
select l;

//order the list by birthdate and lastname
var orderByMultiple =
from l
in listOfPerson
orderby l.BirthDate descending, l.LastName ascending
select l;

//take three records
var takeThree = listOfPerson.Take(3);

//go to the 10th record and then take 3 records from there
var skipTenTakeThree = listOfPerson.Skip(10).Take(3);

//skip up until the Lastname is not equal to Thornton
var skipWhile = listOfPerson.SkipWhile(n => n.LastName != "Thornton");

P.S: There's more LINQ examples at the MSDN website.

 

Monday, December 17, 2007 8:36:31 PM (GMT Standard Time, UTC+00:00) #    Comments [0]  | 

 

NBA + SilverLight = Awesome#

Wow, NBA.com is now joining the silverlight bandwagon.

NEW YORK — Dec. 10, 2007 — The National Basketball Association (NBA) will employ Microsoft Silverlight on NBA.com to further enhance the online video experience for NBA fans around the world. Microsoft Silverlight, a cross-browser, multiplatform plug-in for delivering the next generation of media experiences and rich interactive applications for the Web, will also be utilized on WNBA.com and NBADevelopmentLeague.com.

NBA.com will feature a full-screen NBA photo gallery, offer video highlights and deliver additional interactive applications throughout the site using Microsoft Silverlight. Through the use of Microsoft Corp.’s new application, the NBA will be able to provide further access to its extensive digital video library, integrate the video experience seamlessly into the site, and ultimately provide fans with access to more online video features.

Read the full article here...

I'm a big NBA fan and i frequently visit the site (atleast 4 times a day). Basketball is one of the most popular sports in the world and this partnership I think would greatly boost the adoption of Silverlight in the mainstream.

One more reason why i should kick my gears up another notch with silverlight.

Wednesday, December 12, 2007 10:36:34 PM (GMT Standard Time, UTC+00:00) #    Comments [0]  | 

 

Surprising news of the day: Outsourcing pregnancies#
I saw this on MSN today...

Surrogate Mothers: Womb for Rent

Customer service, tech support...these days we outsource everything to India. So why not pregnancy? Here is a report on the growing number of Indian women willing to carry an American child.

Woah...
Tuesday, December 11, 2007 10:47:23 PM (GMT Standard Time, UTC+00:00) #    Comments [0]  | 

 

How do you expect to get results from this?#

I just saw this from my URL reffer list and it made me laugh.

Heheheh! How do you expect to get a result from this? Does the person expect to automatically get a list of all the people who attended the wedding?

Tuesday, December 11, 2007 8:31:25 PM (GMT Standard Time, UTC+00:00) #    Comments [0]  | 

 

List SQL Servers using SqlDataSourceEnumerator#
I wrote an article a few years ago using SQL SMO and just realized today that I can also list SQL Severs without importing an additional assembly to my project(Microsoft.SqlServer.Management.Smo) by using the SqlDataSourceEnumerator class. SqlDataSourceEnumerator is a class that provides a mechanism for enumerating all intances of SQL Server in a given network. SqlDataSourceEnumerator exposes a method called GetDataSources() that returns a DataTable containing the list of SQL Servers and some basic information about the server
.NET | Fun Stuff | SQL
Tuesday, December 11, 2007 7:39:31 PM (GMT Standard Time, UTC+00:00) #    Comments [0]  | 

 

I just got some Microsoft Lovin'#

A few days ago in Twitterland, Tim Heuer had a contest. He said that whoever twitts him first would get a Microsoft Vista and Ofiice 2007 Ultimate... I quickly sent him a twit but sadly me efforts fell short. My friend Jon Galloway beat me by a second and he officially won... Jon feeling the pain of my defeat sent me a message saying that I can have the prize because he already have an MSDN subscription. Sweet!

Oh boy! That made my day!

Just today I got an email from Tim telling me that he already sent me the package and my eyes got big because it has some extras include in it.

   "package en route: DHL Tracking #248211XXXXX Sent 12/07/07 to Keith Rull
includes: Vista Ultimate, Office Ultimate, Expression Studio and VS2008 Pro as well as some stickers."

Wooohoooh! That's what I call Microsoft Lovin'! Thanks Tim and Jon! Now my Christmas list is almost complete... hmmm.. I wonder who's going to give me a Zune and an XBOX. :)

Now, onwards to SilverLight!

*update* [20071211]: I got the package from Tim yesterday :) Awesome! Now I don't have any excuse to neglect WPF. Thanks Tim!

Friday, December 07, 2007 10:50:23 PM (GMT Standard Time, UTC+00:00) #    Comments [4]  | 

 

NetBeans 6.0 is out..#

...and it has pure Ruby goodness tied into it! I think I'm going to wash my .NET hands today with Neatbens SOAp enhancements. Congratulations to the great folks from NetBeans! You definetely nailed it this time.

From their official press release:

The focus of NetBeans IDE 6.0 is superior developer productivity with a smarter, faster editor, and the integration of all NetBeans products into one IDE. NetBeans IDE 6.0 features Ruby/JRuby/Ruby on Rails support, enhancements for improved Swing development, a new Visual Game Designer, updated Data Binding support, integrated Profiling, and more. The new installer lets you customize your download preferences--use it to choose the features and runtimes you need.
Highlights of NetBeans IDE 6.0 are:

Java
* Swing GUI Builder
* Intelligent Editor
* Profiler
* Debugger
* Updated Platform APIs

C/C++
* C/C++ Projects and Templates
* Source Code Editor
* Multiple Configurations
* Class Hierarchy Browser
* File Navigation
Ruby
* Ruby on Rails Support
* JRuby Runtime
* Code Completion
* Debugger
* Refactoring
Mobility
* Game Builder
* Device Fragmentation
* SVG Graphics
* Web Services
* Handheld Device / Set Top Box
Web & Java EE
* Visual JSF Design
* Enhanced JavaScript
* AJAX Enabled Components
* CSS Editor
* Web Services & SOA
SOA
* XML Schema Editor, XSLT Designer
* WSDL Designer
* BPEL Designer
* Service Assembly Editor
* Deploy to JBI compliant runtime

Awesome! Really awesome! I've been using Netbeans on the side(due to my obedience with .NET) and it has been a great experience for me. I have used Java IDEs in the past(Visual Cafe 4 anyone?) and i must say that Netbeans has come along way since the days of old when Eclipse elitist call Netbeans a "a tool for non-serious java developers". I think this release has proven that NetBeans is valid alternative against the big boys(Eclipse & IntelliJ among others).

Now,  onwards to a cup of Java. ;)

Tuesday, December 04, 2007 11:37:22 PM (GMT Standard Time, UTC+00:00) #    Comments [0]  | 

 

What's wrong with Excel 2007?#

I was working on a report today when I opened my Excel 2007 and this is all i got:

To my surprise there was no toolbar. No menu. No spreadsheet tab. Nothing. All i got was a window with the manification option showing on top of the form. I right-clicked on the bar and this is what i got:

What in the world happened? This was working fine a few days ago! Arrrgh! :( Good thing there is Google Spreadsheet handy!

Tuesday, December 04, 2007 5:56:45 AM (GMT Standard Time, UTC+00:00) #    Comments [0]  | 

 

Are you a VB.NET Fanboy? Then come to ILoveVB.NET!#

I'm still a big fan of VB.NET even if I haven't touched a single VB.NET code in a year and one the biggest VB.NET fanboy I know has just started a website all about the good things you can do with VB.NET. Chris Williams (VB.NET MVP) has just started a website called ILoveVB.NET. The idea is to build a community that would champion the cause of VB.NET(which is to make the world known that VB.NET is a first class programming language and not a code kiddies toy anymore).

Here's the official message from Chris Williams:

This is the place where we show off all the amazingly cool stuff you can do with VB.NET.

If you're passionate about VB.NET, or you have an interesting project or maybe you're providing community support to a technology that doesn't currently have language parity, then you've come to the right place. We will gladly host your project and blog(s).

If you're looking for answers, you may find them here as well. If you're tired of looking everywhere for code samples and only finding C#, keep checking back here. We're making contact with the product teams and working towards getting the samples and SDKs you want.

Once again, thank you for stopping by. If you need anything, feel free to ask.

Chris Williams

Man, I bet you Paul, Carl, Bill and the VB.NET MVPs are going to be excited about this!

Wednesday, November 28, 2007 7:20:57 PM (GMT Standard Time, UTC+00:00) #    Comments [2]  | 

 

Generating random strings in C# and VB.NET revisited#

Somebody sent me an email today asking me about an article I wrote a few years ago detailing how to generate random strings and numbers in C# and VB.NET. He asked me if I could add function to the code that creates a random character set to be used as a base for the allowed characters in the random string. I went on and hammered the solution and this what I built for him. I don't have enough time to explain the whole thing but I hope the code comments I added would be good enough to understand what I did with the code.

[----------------- C# Version -----------------]

using System;
using System.Collections.Generic;
using System.Text;

namespace KeithRull.ConsoleCentral
{
   class RandomStrings
   {
      //our default string size
      private const int CONST_MaxStringLenght = 10;

      //our default character string set
      private const string CONST_AllowedCharacterLiterals 
         = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";

      //our randomizer
      Random randomNumber = new Random();

      /// <summary>
      /// Generate a random string using the default options
      /// </summary>
      /// <returns>the random string</returns>
      public string GenerateRandomString()
      {
         return GenerateRandomString(CONST_MaxStringLenght);
      }

      /// <summary>
      /// Create a random string based on a specified lenght
      /// </summary>
      /// <param name="lenght">the lenght of the desired lenght of the random string</param>
      /// <returns>the randomized string</returns>
      public string GenerateRandomString(int lenght)
      {
         return GenerateRandomString(lenght, CreateRandomStringSet());
      }

      /// <summary>
      /// Creates a random string based on a specific lenght and character set
      /// </summary>
      /// <param name="lenght">the lenght of the desired lenght of the random string</param>
      /// <param name="charsToUse">character set to use</param>
      /// <param name="randomizeSourceSet">defines whether the source set should be scrambled</param>
      /// <returns>the random string</returns>
      public string GenerateRandomString(int lenght, string charsToUse, bool randomizeSourceSet)
      {
         string randomString = String.Empty;

         if (randomizeSourceSet) {
            //scramble and jumble it
            randomString = GenerateRandomString(lenght, CreateRandomStringSet(charsToUse));
         }
         else {
            //use the default charset
            randomString = GenerateRandomString(lenght, charsToUse);
         }

         return randomString;
      }

      /// <summary>
      /// Creates a random string based on a specific lenght and character set
      /// </summary>
      /// <param name="lenght">the lenght of the desired lenght of the random string</param>
      /// <param name="charsToUse">character set to use</param>
      /// <returns>the random string</returns>
      public string GenerateRandomString(int lenght, string charsToUse)
      {
         //Create a new StringBuilder that would hold the random string.
         StringBuilder randomString = new StringBuilder();

         //Create a variable to hold the generated charater.
         char appendedChar;

         //Create a loop that would iterate from 0 to the specified value of intLenghtOfString
         for (int i = 0; i <= lenght; ++i)
         {
            int characterIndex = Convert.ToInt32(randomNumber.Next(i, charsToUse.Length - i));
            //Generate the char and assign it to appendedChar
            appendedChar = charsToUse[characterIndex];
            //Append appendedChar to randomString
            randomString.Append(appendedChar);
         }
         //Convert randomString to String and return the result.
         return randomString.ToString();
      }

      /// <summary>
      /// Returns a random set of characters based on the default literal set
      /// </summary>
      /// <returns>the random string</returns>
      private string CreateRandomStringSet()
      {
         //just use the default character set
         return CreateRandomStringSet(CONST_AllowedCharacterLiterals);
      }

      /// <summary>
      /// A function that returns a new set of characters based on an input set
      /// </summary>
      /// <param name="allowedCharacters">the source set</param>
      /// <returns>the new collection of characters</returns>
      private string CreateRandomStringSet(string allowedCharacters)
      {
         string randomizedString = String.Empty;

         //get a random string set size
         int randomSetLenght = allowedCharacters.Length * randomNumber.Next(1, CONST_MaxStringLenght);

         //while lenght of the random set is not the same as the source string lenght
         while (randomizedString.Length != randomSetLenght)
         {
            //add a new character
            randomizedString += GetRandomCharFromString(allowedCharacters);
         }

         //return our random string
         return randomizedString;
      }

      /// <summary>
      /// Gets a character from the the input string
      /// </summary>
      /// <param name="allowedCharacters">source string</param>
      /// <returns>a random character</returns>
      private char GetRandomCharFromString(string allowedCharacters)
      {
         return allowedCharacters[randomNumber.Next(allowedCharacters.Length - 1)];
      }
   }
}

[----------------- C# Usage -----------------]

using System;
using System.Collections.Generic;
using System.Text;

namespace KeithRull.ConsoleCentral
{
   class Program
   {
      static void Main(string[] args)
      {
         RandomStrings r = new RandomStrings();

         Console.WriteLine(r.GenerateRandomString());
         Console.WriteLine(r.GenerateRandomString(10));
         Console.WriteLine(r.GenerateRandomString(10, "qwerttyuioplkjhgfdsazxcvbnm1234567890QWERTYUIOPLKJHGFDSAZXCVBNM"));
         Console.WriteLine(r.GenerateRandomString(10, "[]{}<>!@#$%^&*()qwerttyuioplkjhgfdsazxcvbnm1234567890", true));
         Console.WriteLine(r.GenerateRandomString(10, "qwerttyuioplkjhgfdsazxcvbnm1234567890QWERTYUIOPLKJHGFDSAZXCVBNM", false));

         Console.ReadLine();
      }
   }
}

[----------------- VB.NET Version -----------------]

Imports System
Imports System.Collections.Generic
Imports System.Text

Namespace KeithRull.ConsoleCentral 
   Class RandomStrings 
      Private Const CONST_MaxStringLenght As Integer = 10 
      Private Const CONST_AllowedCharacterLiterals As String = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890" 

      Private randomNumber As New Random() 

      ''' <summary> 
      ''' Generate a random string using the default options 
      ''' </summary> 
      ''' <returns>the random string</returns> 
      Public Function GenerateRandomString() As String 
         Return GenerateRandomString(CONST_MaxStringLenght) 
      End Function 

      ''' <summary> 
      ''' Create a random string based on a specified lenght 
      ''' </summary> 
      ''' <param name="lenght">the lenght of the desired lenght of the random string</param> 
      ''' <returns>a random string</returns> 
      Public Function GenerateRandomString(ByVal lenght As Integer) As String 
         Return GenerateRandomString(lenght, CreateRandomStringSet()) 
      End Function 

      ''' <summary> 
      ''' Creates a random string based on a specific lenght and character set 
      ''' </summary> 
      ''' <param name="lenght">the lenght of the desired lenght of the random string</param> 
      ''' <param name="charsToUse">character set to use</param> 
      ''' <param name="randomizeSourceSet">defines whether the source set should be scrambled</param> 
      ''' <returns></returns> 
      Public Function GenerateRandomString(ByVal lenght As Integer, ByVal charsToUse As String, ByVal randomizeSourceSet As Boolean) As String 
         Dim randomString As String = [String].Empty 

         If randomizeSourceSet Then 
            'scramble and jumble it 
            randomString = GenerateRandomString(lenght, CreateRandomStringSet(charsToUse)) 
         Else 
            'use the default charset 
            randomString = GenerateRandomString(lenght, charsToUse) 
         End If 

         Return randomString 
      End Function 

      Public Function GenerateRandomString(ByVal lenght As Integer, ByVal charsToUse As String) As String 
         'Create a new StringBuilder that would hold the random string. 
         Dim randomString As New StringBuilder() 

         'Create a variable to hold the generated charater. 
         Dim appendedChar As Char 
         For i As Integer = 0 To lenght 

            'Create a loop that would iterate from 0 to the specified value of intLenghtOfString 
            Dim characterIndex As Integer = Convert.ToInt32(randomNumber.[Next](i, charsToUse.Length - i)) 
            'Generate the char and assign it to appendedChar 
            appendedChar = charsToUse(characterIndex) 
            'Append appendedChar to randomString 
            randomString.Append(appendedChar) 
         Next 
         'Convert randomString to String and return the result. 
         Return randomString.ToString() 
      End Function 

      ''' <summary> 
      ''' Returns a random set of characters based on the default literal set 
      ''' </summary> 
      ''' <returns></returns> 
      Private Function CreateRandomStringSet() As String 
         Return CreateRandomStringSet(CONST_AllowedCharacterLiterals) 
      End Function 

      ''' <summary> 
      ''' A function that returns a new set of characters based on an input set 
      ''' </summary> 
      ''' <param name="allowedCharacters">the source set</param> 
      ''' <returns>the new collection of characters</returns> 
      Private Function CreateRandomStringSet(ByVal allowedCharacters As String) As String 
         Dim randomizedString As String = [String].Empty 

         'get a random string set size 
         Dim randomSetLenght As Integer = allowedCharacters.Length * randomNumber.[Next](1, CONST_MaxStringLenght) 

         'while lenght of the random set is not the same as the source string lenght 
         While randomizedString.Length <> randomSetLenght 
            'add a new character 
            randomizedString += GetRandomCharFromString(allowedCharacters) 
         End While 

         'return our random string 
         Return randomizedString 
      End Function 

      ''' <summary> 
      ''' Gets a character from the the input string 
      ''' </summary> 
      ''' <param name="allowedCharacters">source string</param> 
      ''' <returns>a random character</returns> 
      Private Function GetRandomCharFromString(ByVal allowedCharacters As String) As Char 
         Return allowedCharacters(randomNumber.[Next](allowedCharacters.Length - 1)) 
      End Function 
   End Class
End Namespace

[----------------- VB.NET Usage -----------------]

Imports System
Imports System.Collections.Generic
Imports System.Text

Namespace KeithRull.ConsoleCentral 
   Class Program 
      Private Shared Sub Main(ByVal args As String()) 
      Dim r As RandomStrings = New RandomStrings() 

      Console.WriteLine(r.GenerateRandomString()) 
      Console.WriteLine(r.GenerateRandomString(10)) 
      Console.WriteLine(r.GenerateRandomString(10, "qwerttyuioplkjhgfdsazxcvbnm1234567890QWERTYUIOPLKJHGFDSAZXCVBNM")) 
      Console.WriteLine(r.GenerateRandomString(10, "[]{}<>!@#$%^&*()qwerttyuioplkjhgfdsazxcvbnm1234567890", True)) 
      Console.WriteLine(r.GenerateRandomString(10, "qwerttyuioplkjhgfdsazxcvbnm1234567890QWERTYUIOPLKJHGFDSAZXCVBNM", False)) 

      Console.ReadLine() 
      End Sub 
   End Class
End Namespace

[----------------- Screenshot -----------------]

And that's how you create random strings in C# and VB.NET. Interested in the source code? You can download them here. RandomStrings.cs (4.61 KB) | RandomStrings.vb (5 KB)

Wednesday, November 28, 2007 6:08:02 PM (GMT Standard Time, UTC+00:00) #    Comments [1]  | 

 

All content © 2010, Keith Rull
On this page
This site
Calendar
<December 2007>
SunMonTueWedThuFriSat
2526272829301
2345678
9101112131415
16171819202122
23242526272829
303112345
Archives
Sitemap
Blogroll OPML
Disclaimer

Powered by: newtelligence dasBlog 2.3.9074.18820

The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

Send mail to the author(s) E-mail

Theme design by Jelle Druyts


Pick a theme: