开发者

Is this matching from Scala is available in C#?

I found nice little one example of Scala today. Something like:

(1 to 100) map { x =>   
  (x % 2, x % 6) match {  
    case (0,0) => "First"
    case (0,_) => "Second"    
    case (_,0) => "Third"    
    case _ => x toString    
  }
} foreach println
开发者_开发知识库

And i wonder if I could do something similar in C#. I tried to search on my own but it's hard since I don't know name of this expression. It seems pretty useful. So can I do this in C#?


Pattern matching is not available in C#.

But you can use Nemerle .Net language which supports Pattern Matching and many other great stuff which C# doesn't support.

foreach (x in $[1 .. 100])
{
   Console.WriteLine(
     match((x % 2, x % 6))
     {
       | (0, 0) => "First"
       | (0, _) => "Second"
       | (_, 0) => "Third"
       | _      => x.ToString()
     })
}


It's called (functional) pattern matching, and is a hallmark of functional programming languages such as Scala, F#, and Haskell. http://codebetter.com/matthewpodwysocki/2008/09/16/functional-c-pattern-matching/ discusses how to simulate F#'s version of it in C#.


Since I don't know Scala, I can't verify that this does the same thing, but you can probably base your code off this.

Enumerable.Range(1, 100)
    .Select(x => new {original = x, two = x % 2, six = x % 6})
    .Select(x =>
    {
        if (x.two == 0 && x.six == 0)
            return "First";
        else if (x.two == 0)
            return "Second";
        else if (x.six == 0)
            return "Third";
        else
            return x.original.ToString();
    }).ToList().ForEach(s => Console.WriteLine(s));

Outputs:

1
Second
3
Second
5
First
7
Second
9
Second
...
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜