IronShay

Ironing code, geek t-shirts and even presentations!

NAVIGATION - SEARCH

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 (5) -

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"

Reply

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();

Reply

Australia Irish reddy

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

Reply

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" });

Reply

"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

Reply

Pingbacks and trackbacks (4)+

Add comment