8
9

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.

C#でforeachをForEachしまくる

Posted at

foreachとForEach

UnityでC#触るくらいなので.NETがどうとかはよく知らない。
イテラブルなやつらはみなforeachでループ出来るけどForEach関数が用意されててループがラムダ式で書けるのはList<T>型だけ。

何でもかんでもForEach

せっかく推論型でvarとかで型をあんまし意識しないで書いてるのにForEachがメンバになくて、ああーこれはList<T>型じゃないのかーってがっかりしないように

CollectionExtensions.cs
using System;
using System.Collections.Generic;

public static class CollectionExtensions {
	public static void ForEach<T>(this IEnumerable<T> enumerable, Action<T> action) {
		foreach (var elm in enumerable) action(elm);
	}
}

ってファイルを書いとく。
これでForEachスタンバイ。

使う

例えばディレクトリ内を削除するコード

private static void DeleteDirectory(string path) {
		foreach (var i in Directory.GetDirectories(path)) {
			DeleteDirectory(i);
		}
		foreach (var i in Directory.GetFiles(path)) {
			File.Delete(i);
		}
		Directory.Delete(path);
	}

が、こうなる

private static void DeleteDirectory(string path) {
	Directory.GetDirectories(path).ForEach(obj => DeleteDirectory(obj));
	Directory.GetFiles(path).ForEach(obj => File.Delete(obj));
	Directory.Delete(path);
}

更にメソッドチェーンでこうも書ける

private static void DeleteDirectory(string path) {
		Directory.GetDirectories(path).ForEach(DeleteDirectory);
		Directory.GetFiles(path).ForEach(File.Delete);
		Directory.Delete(path);
	}

コンパクト。

8
9
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
8
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?