문제

현재 요소의 키를 어떻게 얻나요? foreach C#의 루프?

예를 들어:

PHP

foreach ($array as $key => $value)
{
    echo("$value is assigned to key: $key");
}

C#에서 하려는 작업은 다음과 같습니다.

int[] values = { 5, 14, 29, 49, 99, 150, 999 };

foreach (int val in values)
{
    if(search <= val && !stop)
    {
         // Set key to a variable
    }
}
도움이 되었습니까?

해결책

그라우엔울프의 방식 배열을 사용하여 이 작업을 수행하는 가장 간단하고 효율적인 방법은 다음과 같습니다.

for 루프를 사용하거나 각 패스에서 증가하는 임시 변수를 만듭니다.

물론 다음과 같습니다.

int[] values = { 5, 14, 29, 49, 99, 150, 999 };

for (int key = 0; key < values.Length; ++key)
  if (search <= values[key] && !stop)
  {
    // set key to a variable
  }

.NET 3.5를 사용하면 보다 기능적인 접근 방식을 취할 수도 있지만 사이트에서는 좀 더 장황하므로 몇 가지 방법에 의존할 가능성이 높습니다. 지원 기능 ~을 위한 방문 IEnumerable의 요소입니다.이것이 필요한 전부라면 과잉이지만 수집 처리를 많이 하는 경향이 있다면 편리합니다.

다른 팁

열쇠를 얻으려면 다음을 읽어보세요.index)를 사용하려면 for 루프를 사용해야 합니다.실제로 키/값을 보관하는 컬렉션을 갖고 싶다면 HashTable이나 Dictionary(Generic을 사용하려는 경우)를 사용하는 것이 좋습니다.

Dictionary<int, string> items = new  Dictionary<int, string>();

foreach (int key in items.Keys)
{
  Console.WriteLine("Key: {0} has value: {1}", key, items[key]);
}

도움이되기를 바랍니다. 타일러

DictionaryEntry 및 KeyValuePair를 사용하면 다음과 같습니다.

기반
MSDN

IDictionary<string,string> openWith = new Dictionary<string,string>()
{
   { "txt", "notepad.exe" }
   { "bmp", "paint.exe" }
   { "rtf", "wordpad.exe" }
};

foreach (DictionaryEntry de in openWith)
{
    Console.WriteLine("Key = {0}, Value = {1}", de.Key, de.Value);
}

// also

foreach (KeyValuePair<string,string> de in openWith)
{
    Console.WriteLine("Key = {0}, Value = {1}", de.Key, de.Value);
}

관련 SO 질문:KeyValuePair VS DictionaryEntry

아쉽게도 이를 수행할 수 있는 기본 제공 방법이 없습니다.for 루프를 사용하거나 각 패스에서 증가하는 임시 변수를 만듭니다.

나는 이 질문의 다른 버전에서 이에 대답했습니다.

Foreach는 ienumerable을 구현하는 컬렉션을 반복하는 것입니다.컬렉션에서 getEnumerator를 호출하여 열거자를 반환합니다.

이 열거 자에는 방법과 속성이 있습니다.

* MoveNext()
* Current

현재 열거자가 켜져있는 객체를 반환하고 Movenext는 다음 객체로 현재 업데이트됩니다.

분명히, 지수의 개념은 열거의 개념과는 외국이며, 수행 할 수 없습니다.

이로 인해 대부분의 컬렉션은 인덱서 및 FOR 루프 구조를 사용하여 트래버스 할 수 있습니다.

로컬 변수로 인덱스를 추적하는 것과 비교 하여이 상황에서 For Loop을 사용하는 것이 좋습니다.

foreach 루프의 현재 반복 인덱스를 어떻게 얻나요?

실제로 배열을 반복하려면 클래식 for(;;) 루프를 사용해야 합니다.그러나 PHP 코드로 달성한 유사한 기능은 사전을 사용하여 C#에서도 다음과 같이 달성할 수 있습니다.

Dictionary<int, int> values = new Dictionary<int, int>();
values[0] = 5;
values[1] = 14;
values[2] = 29;
values[3] = 49;
// whatever...

foreach (int key in values.Keys)
{
    Console.WriteLine("{0} is assigned to key: {1}", values[key], key);
}

확장 메서드를 사용하여 이 기능을 직접 구현할 수 있습니다.예를 들어, 다음은 목록에서 작동하는 확장 메서드 KeyValuePairs의 구현입니다.

public struct IndexValue<T> {
    public int Index {get; private set;}
    public T Value {get; private set;}
    public IndexValue(int index, T value) : this() {
        this.Index = index;
        this.Value = value;
    }
}

public static class EnumExtension
{
    public static IEnumerable<IndexValue<T>> KeyValuePairs<T>(this IList<T> list) {
        for (int i = 0; i < list.Count; i++)
            yield return new IndexValue<T>(i, list[i]);
    }
}

이 문제에 대해 제가 방금 생각해낸 해결책은 다음과 같습니다.

원본 코드:

int index=0;
foreach (var item in enumerable)
{
    blah(item, index); // some code that depends on the index
    index++;
}

업데이트된 코드

enumerable.ForEach((item, index) => blah(item, index));

확장 방법:

    public static IEnumerable<T> ForEach<T>(this IEnumerable<T> enumerable, Action<T, int> action)
    {
        var unit = new Unit(); // unit is a new type from the reactive framework (http://msdn.microsoft.com/en-us/devlabs/ee794896.aspx) to represent a void, since in C# you can't return a void
        enumerable.Select((item, i) => 
            {
                action(item, i);
                return unit;
            }).ToList();

        return pSource;
    }

myKey = Array.IndexOf(values, val);

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top