概要
LINQで使える小技を忘れない為のチートシート
foreachでIndexを扱いたい場合のSelect
- 匿名クラスを使用
Select+foreach
List<string> aryString = new List<string>() { "Test1", "Test2", "Test3" };
foreach(var indexString in aryString.Select((text,index) => new { Text = text, Index = index }))
{
Console.WriteLine($"Index = {indexString.Index}, Text = {indexString.Text}");
}
Result
Index = 0, Text = Test1
Index = 1, Text = Test2
Index = 2, Text = Test3
- ValueTupleを使用
Select+foreach
List<string> aryString = new List<string>() { "Test1", "Test2", "Test3" };
foreach(var (text,index) in aryString.Select((text,index) => (text, index)))
{
Console.WriteLine($"Index = {index}, Text = {text}");
}
Result
Index = 0, Text = Test1
Index = 1, Text = Test2
Index = 2, Text = Test3