2
1

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 1 year has passed since last update.

LINQ小技メモ

Last updated at Posted at 2023-05-02

概要

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
2
1
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
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?