Skip to content
This repository has been archived by the owner on Oct 14, 2019. It is now read-only.

Monads for collections

sergun edited this page Aug 7, 2012 · 1 revision

Do

Enumerable

Before

IEnumerable<string> data = ...;
// ...
if (data != null)
{
  foreach (var d in data)
  {
    Console.WriteLine(d);
  }
}

After

IEnumerable<string> data = ...;
// ...
data.Do(d=>Console.WriteLine(d));

Dictionary

Before

IDictionary<int, string> data = ... ;
// ...
if (data != null)
{
  foreach (var d in data)
  {
     Console.WriteLine("{0} - {1}", d.Key, d.Value);
  }
}

After

IDictionary data = ... ;
// ...
data.Do((k,v)=>Console.WriteLine("{0} - {1}", k, v));

With

Enumerable

Before

IEnumerable<string> data = ...;
// ...
if (data != null)
{
  var result = data.Select(d=>d.Trim());
}

After

IEnumerable<string> data = ...;
// ...
var result = data.With(d=>d.Trim());

Dictionary

Before

IDictionary<int, string> data = ... ;
// ...
if (data != null)
{
  string result;
  if (data.TryGetValue(1, out result) == true)
  {
    Console.WriteLine(result);
  }
}

After

IDictionary<int, string> data = ... ;
// ...
var result = data.With(1);
if (result != null)
{
  Console.WriteLine(result);
}

Return

Dictionary

Before

IDictionary<int, string> data = ... ;
// ...
if (data != null)
{
  string result;
  if (data.TryGetValue(1, out result) == true)
  {
    Console.WriteLine(result);
  }
  else
  {
    Console.WriteLine("Not found");
  }
}

After

IDictionary<int, string> data = ... ;
// ...
Console.WriteLine(data.Return(1, "Not found"));
Clone this wiki locally