LINQ

The more you use LINQ the more you will appreciate its power. The following short code snippet demostrates some thing we might have to be able to do easily when dealing with relational data but not collections in C#.

Write a program that findsany duplicate characters in a string.

Old school of thoughts – Loop through every character in the string while keeping a count on each. This type of algorithm could easily be O(n).

New way – Enter the new world of C#:

List<char> lstTest = "anapple".ToList<char>();
var result = from ss in lstTest
                group ss by ss into gr
                where gr.Count<char>() > 1
                select new { duplicateChar = gr };

foreach (var item in result)
    Console.WriteLine(item.duplicateChar.Key);

Now that’s cool!

發表迴響

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

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / 變更 )

Twitter picture

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

Facebook照片

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

連結到 %s

Follow

Get every new post delivered to your Inbox.