This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
>>> a=[3,6,8,2] | |
>>> for Index,Value in enumerate(a): | |
... print(Index,Value) | |
... | |
0 3 | |
1 6 | |
2 8 | |
3 2 |
หากเราต้องการเขียนเป็น C# ทำได้ตามนี้
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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(); | |
} | |
} | |
} |
จะเห็นได้ว่าใน C# เราจะไม่ใช่ for เหมือน Python ในกรณีที่ต้องการลูปค่าจากค่าที่มีอยู่แล้ว
0 ความคิดเห็น:
แสดงความคิดเห็น