C# のスニペット集
このページは、C# のスニペットなどをまとめる予定のページです。
目次
注意
- コードのライセンスは CC0 (クレジット表示不要、改変可、商用可) です。
スニペット
文字列
フォーマット
var a = 1;
var b = 2;
var s1 = string.Format("a = {0}, b = {1}", a, b); // a = 1, b = 2
var s2 = $"a = {a}, b = {b}"; // a = 1, b = 2
パディング
var a1 = 1;
var s1 = string.Format("{0,4}", a1); // 「 1」
var s2 = $"{a1,4}"; // 上と同じ
var s3 = (a1 + "").PadLeft(4); // 上と同じ
var a1 = 1;
var s1 = string.Format("{0,-4}", a1); // 「 1」
var s2 = $"{a1,-4}"; // 上と同じ
var s3 = (a1 + "").PadRight(4); // 上と同じ
var a1 = 1;
var s1 = string.Format("{0:D4}", a1); // 0001
var s2 = $"{a1:D4}"; // 上と同じ
var s3 = (a1 + "").PadLeft(4, '0'); // 上と同じ
var a1 = 1;
var s1 = (a1 + "").PadRight(4, '0'); // 1000
文字列の検索
var s = "test string";
var b = s.Contains("str");
var s = "test string";
var b = s.StartsWith("test");
var s = "test string";
var b = s.EndsWith("ing");
数値変換
var s = "123";
var n = int.Parse(s); // 失敗時はFormatException
int? n2 = int.TryParse(s, out var v) ? v : null; // 失敗時はnull
var s = "123.45";
var n = double.Parse(s); // 失敗時はFormatException
double? n2 = double.TryParse(s, out var v) ? v : null; // 失敗時はnull
var s = "123.45";
var n = decimal.Parse(s); // 失敗時はFormatException
decimal? n2 = decimal.TryParse(s, out var v) ? v : null; // 失敗時はnull
List
var list1 = new List<string> { "a", "b", "c", "d" };
Dictionary
生成 (初期化)
var dict1 = new Dictionary<string, string>() {
{ "a", "b" },
{ "c", "d" },
};
// 上と同じ
var dict2 = new Dictionary<string, string>() {
["a"] = "b",
["c"] = "d",
};
値の取得
var dict1 = new Dictionary<string, int>() {
["a"] = 1,
["b"] = 2,
};
var a1 = dict1["a"]; // キーが存在しない場合はKeyNotFoundException
int? a2 = dict1.TryGetValue("a", out var v) ? v : null; // キーが存在しない場合はnull
マージ
var dict1 = new Dictionary<string, int>() {
["a"] = 1,
["b"] = 2,
};
var dict2 = new Dictionary<string, int>() {
["a"] = 100,
["c"] = 3,
["d"] = 4,
};
// {"a": 100, "b": 2, "c": 3, "d": 4}
var dict3 = dict1.Concat(dict2).ToLookup(x => x.Key, x => x.Value).ToDictionary(x => x.Key, x => x.Last());
IEnumerable
// record Person(string Name, int Age);
var list1 = new List<Person> {
new Person("taro", 20),
new Person("jiro", 10),
new Person("hanako", 19)
};
var name = string.Join(", ", list1.Select(x => x.Name)); // taro, jiro, hanako
// record Person(string Name, int Age);
var list1 = new List<Person> {
new Person("taro", 20),
new Person("jiro", 10),
new Person("hanako", 19)
};
var list2 = list1.Where(x => x["age"] > 15).ToList();
// record Person(string Name, int Age);
var list1 = new List<Person> {
new Person("taro", 20),
new Person("jiro", 10),
new Person("hanako", 19)
};
var list2 = list1.OrderBy(x => x.Age);
// record Person(string Name, int Age);
var list1 = new List<Person> {
new Person("taro", 20),
new Person("jiro", 10),
new Person("hanako", 19)
};
var list2 = list1.OrderByDescending(x => x.Age);
正規表現
マッチ
var s = "20220102";
if (Regex.IsMatch(s, "^[0-9]{8}$"))
{
}
var s = "20220102";
var m = Regex.Match(s, @"^([0-9]{4})([0-9]{2})([0-9]{2})$");
if (m.Success)
{
var yyyy = m.Groups[1].ToString();
var mm = m.Groups[2].ToString();
var dd = m.Groups[3].ToString();
Console.WriteLine($"{yyyy} {mm} {dd}");
}
var s = "20220102";
var m = Regex.Match(s, @"\A(?<yyyy>[0-9]{4})(?<mm>[0-9]{2})(?<dd>[0-9]{2})\z");
if (m.Success)
{
var yyyy = m.Groups["yyyy"].ToString();
var mm = m.Groups["mm"].ToString();
var dd = m.Groups["dd"].ToString();
Console.WriteLine($"{yyyy} {mm} {dd}");
}
置換
var s1 = "abc123abc";
var s2 = Regex.Replace(s1, "^abc", ""); // 123abc
var dict1 = new Dictionary<string, string> { { "a", "test1" }, { "b", "test2" } };
// "{a} {b} {c}" -> "test1 test2 {c}"
var s = Regex.Replace("{a} {b} {c}", "\\{(.+?)\\}", x =>
{
return dict1.TryGetValue(x.Groups[1].ToString(), out var value) ? value : x.Groups[0].ToString();
});
日時
現在日時
var d1 = DateTime.Now; // ローカル日時
var d2 = DateTime.UtcNow; // UTC
var d3 = DateTimeOffset.Now; // ローカル日時
var d4 = DateTimeOffset.UtcNow; // UTC
タイムゾーン
var utc = TimeZoneInfo.Utc;
var jst = TimeZoneInfo.FindSystemTimeZoneById(RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? "Tokyo Standard Time" : "Asia/Tokyo");
パース
var d1 = DateTime.Parse("2001-02-03T04:05:06");
var d2 = DateTimeOffset.ParseExact("2001/02/03 04:05:06 +09:00", "yyyy/MM/dd HH:mm:ss zzz", CultureInfo.InvariantCulture);
DateTimeOffset d3;
if (!DateTimeOffset.TryParseExact("2001/02/03 04:05:06 +09:00", "yyyy/MM/dd HH:mm:ss zzz", CultureInfo.InvariantCulture, DateTimeStyles.None, out d3))
{
// パース失敗時
}
var d = DateTimeOffset.Parse("2001/02/03T04:05:06+09:00");
フォーマット
var d = DateTime.Parse("2001-02-03T04:05:06");
var s1 = d.ToString("yyyyMMddHHmmss"); // 20010203040506
var s2 = $"{d:yyyyMMddHHmmss}"; // 上と同じ
時間の切り捨て
var d1 = DateTime.Today; // 当日の00:00:00
var d2 = DateTime.Now.Date; // 上と同じ
// DateTimeOffsetで.Dateを使用するとDateTimeになるため下記にする
var d3 = DateTimeOffset.Parse("2001-02-03T04:05:06+07:00");
var d4 = DateTimeOffset.Parse($"{d3:yyyy-MM-ddT00:00:00zzz}"); // 2001-02-03T00:00:00+07:00
月の演算 (加算など)
var d = DateTime.Now;
var d2 = d.AddMonths(1);
var d = new DateTime(2001, 2, 3);
var d2 = d.AddDays(DateTime.DaysInMonth(d.Year, d.Month) - d.Day); // 2001-02-28
月日数の取得
var d = new DateTime(2001, 2, 3);
var daysInMonth = DateTime.DaysInMonth(d.Year, d.Month); // 28
ファイル
文字コード
var utf8 = Encoding.UTF8;
var utf8bom = new UTF8Encoding(true);
//Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
var sjis = Encoding.GetEncoding("Shift_JIS");
パス
var path1 = @"\dir\file.txt";
var dirPath = Path.GetDirectoryName(path1)!; // \dir
var filename = Path.GetFileName(path1); // file.txt
var path2 = Path.Combine(dirPath, "file2.txt"); // \dir\file2.txt
読み込み
var path = @"\tmp\test.txt";
var text = await File.ReadAllTextAsync(path, Encoding.GetEncoding("Shift_JIS"));
var path = @"\tmp\test.txt";
var lines = await File.ReadAllLinesAsync(path, Encoding.GetEncoding("Shift_JIS"));
var path = @"\tmp\test.txt";
var lines = File.ReadLines(path, Encoding.GetEncoding("Shift_JIS"));
foreach (var line in lines) {
//
}
var path = "test.txt";
using (var fs = new FileStream(path, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite))
using (var sr = new StreamReader(fs))
{
var text = await sr.ReadToEndAsync();
}
書き込み
var path = "/dir/sub/sub2/test.txt";
var dirPath = Path.GetDirectoryName(path)!;
if (!Directory.Exists(dirPath))
{
Directory.CreateDirectory(dirPath);
}
File.WriteAllText(path, "あいう", Encoding.GetEncoding("Shift_JIS"));
File.WriteAllText(path, "あいう", new UTF8Encoding(true));
JSON
パース
// using System.Text.Json.Nodes;
var json = "{\"items\": [{\"name\": \"item1\"}]}";
var jsonNode = JsonNode.Parse(json);
var name = jsonNode?["items"]?[0]?["name"]; // item1
文字列化
// using System.Text.Json;
var dict = new Dictionary<string, List<Dictionary<string, object>>> {
["items"] = new()
{
new()
{
["name"] = "item1"
}
}
};
var json = JsonSerializer.Serialize(dict); // {"items":[{"name":"item1"}]}