LoginSignup
5
2

More than 5 years have passed since last update.

(個人的に)よく使うLinq拡張

Last updated at Posted at 2019-03-05

概要

よく使うLinq拡張をまとめました

コード

Index付きforeach

var hoge = new List<int>() { 1, 3, 5 };
foreach (var (index, value) in hoge.WithIndex())
{
    Console.WriteLine($"index: {index}, value: {value}");
}
結果
index: 0, value: 1
index: 1, value: 3
index: 2, value: 5

項目の文字列結合

var hoge = new List<int>() { 1, 3, 5 };
var str1 = hoge.JoinString(":");
Console.WriteLine($"str1: {str1}")
var str2 = hoge.JoinComma();
Console.WriteLine($"str2: {str2}")
結果
str1: 1:3:5
str2: 1,3,5

要素分割foreach

var hoge = new List<int>() { 1, 3, 5 };
foreach (var h in hoge.Chunk(2))
{
    Console.WriteLine($"hoge: {h.JoinComma()}");
}
結果
hoge: 1,3
hoge: 5

要素のランダム取得

var hoge = new List<int>() { 1, 3, 5 };
var rand = new Random();
var h = hoge.Sample(rand);
Console.WriteLine($"h: {h}");
結果例
h: 5
5
2
2

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
2