วันจันทร์ที่ 4 กันยายน พ.ศ. 2560

จาก Python สู่ C# : enumerate ในการลูป for

คนที่ใช้ Python คงคุ้นเคยกับการลูปโดยใช้คำสั่ง enumerate ซึ่งเป็นคำสั่งสำหรับรับค่า index และข้อมูลใน index นั้น แต่ใน C# กลับไม่มีความสามารถนี้ แต่เราสามารถทดแทนความนี้ได้ตามนี้
>>> a=[3,6,8,2]
>>> for Index,Value in enumerate(a):
... print(Index,Value)
...
0 3
1 6
2 8
3 2
view raw enumerate.py hosted with ❤ by GitHub

หากเราต้องการเขียนเป็น C# ทำได้ตามนี้
// GWLlosa's answer in http://stackoverflow.com/questions/521687/c-sharp-foreach-with-index
using System;
using System.Collections.Generic;
using System.Linq;
namespace EnumerateTest {
class Program {
static void Main(string[] args) {
List<int> list = new List<int> {3,6,8,2};
foreach (var it in list.Select((Value, Index) => new {Value, Index})) {
Console.WriteLine("{0}: {1}", it.Index, it.Value);
}
Console.ReadLine();
}
}
}
view raw enumerate.cs hosted with ❤ by GitHub

จะเห็นได้ว่าใน C# เราจะไม่ใช่ for เหมือน Python ในกรณีที่ต้องการลูปค่าจากค่าที่มีอยู่แล้ว

0 ความคิดเห็น:

แสดงความคิดเห็น