Getting the array key in a 'foreach' loop

前端 未结 9 584
别跟我提以往
别跟我提以往 2021-02-03 22:42

How do I get the key of the current element in a foreach loop in C#?

For example:

PHP

foreach ($array as $key => $value)
{
             


        
相关标签:
9条回答
  • 2021-02-03 23:23

    You can implement this functionality yourself using an extension method. For example, here is an implementation of an extension method KeyValuePairs which works on lists:

    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]);
        }
    }
    
    0 讨论(0)
  • 2021-02-03 23:25

    With DictionaryEntry and KeyValuePair:

    Based on
    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);
    }
    

    Releated SO question: KeyValuePair VS DictionaryEntry

    0 讨论(0)
  • 2021-02-03 23:31

    Here's a solution I just came up with for this problem

    Original code:

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

    Updated code

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

    Extension Method:

        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;
        }
    
    0 讨论(0)
  • 2021-02-03 23:31

    myKey = Array.IndexOf(values, val);

    0 讨论(0)
  • 2021-02-03 23:33

    Alas there is no built-in way to do this. Either use a for loop or create a temp variable that you increment on each pass.

    0 讨论(0)
  • 2021-02-03 23:33

    Actually you should use classic for (;;) loop if you want to loop through an array. But the similar functionality that you have achieved with your PHP code can be achieved in C# like this with a Dictionary:

    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);
    }
    
    0 讨论(0)
提交回复
热议问题