Skip to content

Instantly share code, notes, and snippets.

@rbirkby
Created June 2, 2011 17:12
Show Gist options
  • Star 13 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save rbirkby/1004837 to your computer and use it in GitHub Desktop.
Save rbirkby/1004837 to your computer and use it in GitHub Desktop.
10 C# One Liners to Impress Your Friends
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml.Linq;
class TenCSharpOneLiners
{
static void Main()
{
Print("Multiple each item in a list by 2", Enumerable.Range(1, 10).Select(i => i * 2));
Print("Sum a list of numbers", Enumerable.Range(1, 1000).Sum());
var wordlist = new[] { "C#", "and stuff" };
var tweet = "This is an example tweet talking about C# and stuff";
Print("Verify if a word exists in string", wordlist.Any(word => tweet.IndexOf(word) > -1));
Print("Show matched words in string", wordlist.Where(word => tweet.IndexOf(word) > -1));
Print("Read in a File", File.ReadAllBytes("oneliners.exe").Length);
Print("Happy Birthday", Enumerable.Range(1, 4).Select((i) => string.Format("Happy Birthday {0} ", i == 3 ? "dear NAME" : "to You")));
var passed = new List<int>();
var failed = new List<int>();
(from bucket in new[] { passed, failed } from i in new[] { 49, 58, 76, 82, 88, 90 } select new { bucket, i }).ToList().ForEach((tuple) => tuple.bucket.AddRange(Enumerable.Repeat(tuple, 1).Where((tup) => (tup.bucket == passed && tup.i > 60) || (tup.bucket == failed && tup.i <= 60)).Select((tup) => tup.i)));
Print("Filter list of numbers >60", (IEnumerable<int>)passed);
Print("Filter list of numbers <=60", (IEnumerable<int>)failed);
Print("Fetch and Parse an XML web service", XDocument.Load("http://search.twitter.com/search.atom?&q=scala"));
Print("Find minimum in a list", Enumerable.Min(new[] { 14, 35, -7, 46, 98 }));
Print("Find maximum in a list", Enumerable.Max(new[] { 14, 35, -7, 46, 98 }));
Print("Parallel Processing", Enumerable.Range(1, 10).AsParallel().Select((i)=>i*2).AsEnumerable());
Print("Sieve of Eratosthenes", "TODO");
Print("Fizzbuzz", Enumerable.Range(1, 15).Select((i)=>i + (i%3==0?"fizz":"") + (i%5==0?"buzz":"")));
}
static void Print<T>(string desc, T scalar)
{
Console.WriteLine("\n" + desc);
Print(scalar);
}
static void Print<T>(T scalar)
{
Console.WriteLine(scalar);
}
static void Print<T>(string desc, IEnumerable<T> seq)
{
Console.WriteLine("\n" + desc);
foreach (var item in seq)
{
Print(item);
}
}
}
@ciao1092
Copy link

The minifier I used: CSharpMinifier

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment