행 인덱스를 얻는 방법이 있습니까?각각 RowIndex를 얻으려면
예 :
int rowIndex = 0;
foreach (int a in numbers)
{
// Manipulation
rowIndex++;
}
내가 그것을하는 빠른 방법이 있나요
foreach (int a in numbers)
{
a.RowIndex;
}
하고 싶은거야? 어쩌면 확장 방법을 사용할 것인가?
행 인덱스를 얻는 방법이 있습니까?각각 RowIndex를 얻으려면
예 :
int rowIndex = 0;
foreach (int a in numbers)
{
// Manipulation
rowIndex++;
}
내가 그것을하는 빠른 방법이 있나요
foreach (int a in numbers)
{
a.RowIndex;
}
하고 싶은거야? 어쩌면 확장 방법을 사용할 것인가?
는보십시오 항목의 인덱스를 통과 선택의 과부하가있다
foreach (var item in numbers.Select((x,i) => new { Index = i, Value = x })) {
var index = item.Index;
var value = item.Value;
...
}
다음과 같습니다. 이 코드는 인덱스와 값을 모두 포함하는 모든 항목에 대해 새로운 익명 형식을 만듭니다.
구문을 약간 더 쉽게 읽을 수있는 대체 방법은 다음과 같습니다.
public static void ForEach<T>(this IEnumerable<T> source, Action<T,int> del) {
int i = 0;
foreach (var cur in source) {
del(cur, i);
i++;
}
}
numbers.ForEach((x,i) =>
{
// x is the value and i is the index
}
로컬을 정의하고 수동으로 증가시키지 않습니다. 그런 식으로하고 싶지 않은 특별한 이유가 있습니까?
foreach 루프를 고수한다면 이것은 가장 간단한 방법 일 것입니다. 어떤 수준도 아니지만, 여전히 최선의 방법이라고 생각합니다.
int rowIndex = 0;
foreach (int a in numbers)
{
rowIndex++; // You could of course inline this wherever rowIndex first
// gets used, and then simply reference rowIndex (without
// the increment) later.
// ...
}
은 그러나 당신이이 일을 시작하면, 그것은 단지 어쨌든 루프에 대한 일반을 사용하는 것이 아마도 가장 좋은 (하지 않는 한 할 수없는 컬렉션은 물론 IEnumerable
하지 IList
/ICollection
구현하므로).
가능한 중복 [(C#) 현재 foreach 반복의 색인 가져 오기] (http://stackoverflow.com/questions/43021/c-get-index-of-current-foreach-iteration) –
[이 질문의 중복 ] (http://stackoverflow.com/questions/43021/c-get-index-of-current-foreach-iteration)? –