23
22

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Linqで快適な生活を

Posted at

LinqにはSelectやAllなど便利なメソッドがいくつもあるのですが、中でも自分のお気に入りはAggregateです。例えば、リスト内で最大の値を持つ要素のIndexを知りたい場合は以下のように書くことが出来ます。

var l = new List<int>() {3, 1, 5, 4, 2};
var maxIdx = l.Select((val, idx) => new { V = val, I = Idx }).Aggregate((max, working) => (max.V > working.V) ? max : working).I;
// maxIdx は 2となる

上記の例では、OrderByDescendingを使った方が分かりやすいかもしれませんが、もっと複雑な条件にも対応できるのがAggregateの良いところですね。Dictionaryなどにも対応できるので、今日も快適な生活を送れます。また、途中の無名クラスへのselectも常套手段だったりします。

23
22
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
23
22

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?