5
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Elixir使いがC#のLINQを学ぶ その1

Posted at

C#のLINQを15年ぶりに再学習をしてます
ここ4年ぐらいElixirを使っているため、Elixirと比較して学習してみます

Elixirでよく使われる
Enum.mapとEnum.reduceの代わりをC#で再現をしたいです

Elixir C#
Enum.map Select
Enum.reduce Aggregate

Enum.map

お題:各数字を2倍する

Elixir
iex> Enum.map([1, 2, 3], fn x -> x * 2 end)
[2, 4, 6]

C#
List<int> v = [1,2,3];
var ret = v.Select(x => x * 2);
Console.WriteLine(String.Join(", ", ret));

2, 4, 6

お題:値の部分を取得して各数字をマイナスにする

Elixir
iex> Enum.map([a: 1, b: 2], fn {k, v} -> {k, -v} end)
[a: -1, b: -2]
Dictionary<string, int> d = new()
{
    { "a", 1 },
    { "b", 2 }
};

var ret = d.Select(x => (x.Key, -x.Value));
Console.WriteLine(String.Join(", ", ret));

(a, -1), (b, -2)

Enum.reduce

お題:合計を求める

Elixir
iex> Enum.reduce([1, 2, 3], 0, fn x, acc -> x + acc end)
6

C#
List<int> v = [1, 2, 3];
var ret = v.Aggregate(0, (acc, x) => x + acc);
Console.WriteLine(ret);

6

お題:値の部分を取得して合計を求める

Elixir
iex> Enum.reduce(%{a: 2, b: 3, c: 4}, 0, fn {_key, val}, acc -> acc + val end)
9
C#
Dictionary<string, int> d = new()
{
    { "a", 2 },
    { "b", 3 },
    { "c", 4 },
};

var ret = d.Aggregate(0, (acc, x) => x.Value + acc);
Console.WriteLine(ret);

9

感想

1つの言語を知っていると他の言語に変換が可能です
まずは1つの言語で色々作れるようになることは大事だなーと実感しました
15年前だったら、すんなり理解できなかったかも

5
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?