C# One Liners

I love programming languages. I think they are beautiful. One of the best things about learning different programming languages is finding the different approaches and techniques of each language. This also allows you to incorporate them into other programming languages. One of my favorite languages is Ruby, and Rubyists have this habit of writing meaningful code in one line, AKA “one liner”. C#-ers don’t do one-liners very much, probably because they couldn’t write cool one-liners till not so long ago.

BUT! this has all changed with the arrival of LINQ. The first time you see it you go “WHAT THE ****!?!?!?##@@!??!??”, then you go “hmmmmm” and eventually you have a silly happy look on your face and it seems like everything you can pronounce is “wow” and “cool!”. That’s why my nickname for LINQ is “CDD” – Coolness Driven Development.
So for this post I’ve gathered some cool C# one-liners that I’ve put together with the help of LINQ and features of the C# language. Have more? add a comment!

Filter lists

var list = new List<string>() {"Asia", "Africa", "North America", "South America", "Antartica", "Europe", "Australia"};

// Get all the items from the list that start with
// an 'A' and have 'r' as the 3rd character
var filteredList = list.Where(item => item.StartsWith("A")).Where(item => item[2] == 'u').ToList();

 

Create a new list from the first items of another list

// Take the first 3 items from list 'list' and create a new list with them
var shortList = list.Take(3).ToList();

 

Remove duplicate items from a list

var listWithoutDuplicates = list.Distinct().ToList();

 

Print all items in a list

list.ForEach(Console.WriteLine);

 

Cool string counting stuff

var str = "H1e2l3l4l5o6";
// Count all digits in a string
var numOfDigits = str.Count(char.IsDigit);
// Count all lowercase characters in a string
var numOfLowerCase = str.Count(char.IsLower);
// Count all uppercase characters within a string
var numOfUpperCase = str.Count(char.IsUpper);

 

Comparing two lists

var list = new List<string>() { "Asia", "Africa", "North America", "South America", "Antartica", "Europe", "Australia" };
var list2 = new List<string> {"Africa", "South America", "Antartica", "Foo"};

// Get all items in the list that do NOT have matching items on a different list
var list3 = list.Except(list2).ToList();

// Get all items in the list that have matching items on a different list
list3 = list.Intersect(list2).ToList();

Convert all items in a list

string[] numbersAsText = new[] {"1", "2", "3"};
int[] numbers = numbersAsText.Select(n => Convert.ToInt32(n)).ToArray();
numbers.ToList().ForEach(Console.WriteLine);

 

Do heavy processing of parts of groups in threads

var nums = Enumerable.Range(1, 100);
Parallel.ForEach(nums.GroupBy(num => num%2), numGroup => DoHeavyStuff(numGroup.ToList()));

 

Well, that’s what I have… I bet there are tons more. Go ahead C#-ers, it’s your time to shine!
Shay.




Comments

March 13. 2012 02:57 PM

Lulz

I think the first code snippet is wrong, it is supposed to

"Get all the items from the list that start with an 'A' and have 'r' as the 3rd character"

but instead it will "get all items from the list that start with an 'A' and have 'u' as the 3rd character"

Lulz

March 16. 2012 12:25 AM

Hossein

Hi!

great post. this is my one line codes.

string str = "45,43,122,75,34";
int[] values = str.Split(',').Select(o => Convert.ToInt32(o)).ToArray();

Hossein

April 27. 2012 12:00 AM

trackback

Back to Basics: Moving beyond for, if and switch

Scott Hanselman

April 28. 2012 09:18 AM

Irish reddy

Great post. This definTely makes me think twice before using any other control switch

Irish reddy

April 28. 2012 12:09 PM

Pesho

I frequently need to create List of anonymous types for testing purposes.
These 3 lines save a lot of time.

var Customer = new { FirstName = "John", LastName = "Doe" };
var customerList = (new[] { Customer }).ToList();
customerList.Add(new { FirstName = "Bill", LastName = "Smith" });

Pesho

April 28. 2012 03:00 PM

Paul

"I frequently need to create List of anonymous types for testing purposes.
These 3 lines save a lot of time."


For testing purposes I suggest to use a framework for such things like creating fake data.

Take a look into:
- AutoFixture
- AutoPoco

Cheers,
Paul

Paul

June 5. 2012 07:15 AM

trackback

Back to Basics:if,for和switch之外的事情

[原文发表地址]  Back to Basics: Moving beyond for, if and switch [原文发表时间]  2012-04-26 19:59 我访问了很多的客户

Scott Hanselman的中文博客

June 11. 2012 08:30 AM

trackback

回归基础:for,if,switch之外的事情

[原文发表地址] Back to Basics: Moving beyond for, if and switch
[原文发表时间] 2012-04-26 19:59
我访问了很多的客户,查看了大量的代码

Scott Hanselman的中文博客

June 11. 2012 08:36 AM

trackback

回归基础:if,for和switch之外的事情

[原文发表地址]  Back to Basics: Moving beyond for, if and switch [原文发表时间]  2012-04-26 19:59 我访问了很多的客户

Scott Hanselman的中文博客

March 23. 2013 04:53 PM

original site

You must be needing that. I want to know about programming but I just need to learn about the very basic first.

original site

April 17. 2013 11:22 AM

Antoun Sehnaoui

Hello. Very nice blog. Interesting informations.

Antoun Sehnaoui

April 24. 2013 04:56 AM

monster beats

Line Control function: not all with remote control headphones have a call feature, nor is it with a call feature headphones have a volume adjustment, so to understand clearly at the time of purchase and then buy

monster beats

April 30. 2013 02:53 PM

get2tech.com

Thank you for another important article. Where else can you get this information in a comprehensive way of writing? It took me a week, and I am looking for information.

get2tech.com

Add comment


(Will show your Gravatar icon)

  Country flag

biuquote
  • Comment
  • Preview
Loading



Subscribe Subscribe

That's Me!

Hi! I'm Shay Friedman
I'm Shay Friedman - a Visual C#/IronRuby MVP, a consultant and instructor of .NET technologies, author, speaker and new technologies freak
More about me

Contact Me

> Contact page
> Twitter: @ironshay
> LinkedIn profile

Search

Hosted By

I'm hosting this site on Arvixe and I'm very happy with it.
If you're looking for ASP.NET hosting, I highly recommend it
(and if you order from this link I also get some beer money!)
Web Hosting