Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8253273
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 8, 20262026-06-08T00:49:24+00:00 2026-06-08T00:49:24+00:00

I have a string array with strings and a dictionary. String [] str_array; Dictionary<int,

  • 0

I have a string array with strings and a dictionary.

String [] str_array;
Dictionary<int, string> dict = new Dictionary<int, string>();

dict = str_array.toDictionary();

How do I get my array into a dictionary with int and String?
I have seen all those examples with bool, but I need int and string.

The int (key) would be just the actual position of the dictionary (dict.count) and the value would be the value of the array at that position.

edit: thx to all answers but I do not want to iterate over array. I assume that with array.toDictionary the performance would be better than iterating over array and just assigning the value of the array to a dictionary. Arrays might have 5k elements.

edit2: the reason is that i have to pass a dictionary to a method…its REQUIRED. and all my values are within a simple array.

edit3: The most important thing is performance. Maybe iterating over array and assigning values to dict is faster than array.toDictionary, but the problem is that i do not have that little piece of code to benchmark both.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-08T00:49:26+00:00Added an answer on June 8, 2026 at 12:49 am

    First – your problem over performance is interesting and smacks of premature optimisation – as this answer will show, you’re probably looking at a couple of milliseconds difference in performance between a for loop and ToDictionary.

    Unless you are running this in a realtime system I can’t see much of a problem.

    On to the show – the following is a crude benchmark (only real-world timings are reliable) of three (and a half) different ways I can think of to build the dictionary. The first uses the for loop, with the second doing the same but not using the array’s Length property (just for interest); the third and fourth use ToDictionary; one uses a Select and one uses a counter variable (a hybrid):

    [TestMethod]
    public void SomeBenchmark()
    {
        List<double> forLoopTimes = new List<double>();
        List<double> forLoop2Times = new List<double>();
        List<double> toDictionaryTimes = new List<double>();
        List<double> hybridTimes = new List<double>();
    
        string[] array = Enumerable.Range(0, 5000).Select(i => i.ToString()).ToArray();
    
        Dictionary<int, string> dictionary;
    
        int runCount = 5000;
        int arrayLen = array.Length;
    
        while (runCount-- != 0)
        {
            Stopwatch sw = Stopwatch.StartNew();
            dictionary = new Dictionary<int, string>();
            for (int i = 0; i < array.Length; i++)
            {
                dictionary[i] = array[i];
            }
            sw.Stop();
            forLoopTimes.Add(sw.Elapsed.TotalMilliseconds);
    
            sw.Restart();
            dictionary = new Dictionary<int, string>();
            for (int i = 0; i < arrayLen; i++)
            {   //same as before - but using arrayLen instead of property
                dictionary[i] = array[i];
            }
            sw.Stop();
            forLoop2Times.Add(sw.Elapsed.TotalMilliseconds);
    
            sw.Restart();
            dictionary = array.Select((s, i) => new { Key = i, Value = s }).ToDictionary(v => v.Key, v => v.Value);
            sw.Stop();
            toDictionaryTimes.Add(sw.Elapsed.TotalMilliseconds);
    
            int counter = 0;
            sw.Restart();
            dictionary = array.ToDictionary(s => counter++, s => s);
            sw.Stop();
            hybridTimes.Add(sw.Elapsed.TotalMilliseconds);
        }
        Console.WriteLine("for loop average: {0} milliseconds", forLoopTimes.Average());
        Console.WriteLine("for loop(2) average: {0} milliseconds", forLoop2Times.Average());
        Console.WriteLine("ToDictionary average: {0} milliseconds", toDictionaryTimes.Average());
        Console.WriteLine("Hybrid average: {0} milliseconds", hybridTimes.Average());
    }
    

    Results (Release build, and takes about 20 seconds to run on my Dell 2.4Ghz Workstation):

    For loop average: 0.28880804 milliseconds

    For loop(2) average: 0.2773845 milliseconds

    ToDictionary average: 0.479094339999998 milliseconds

    Hybrid average: 0.353655779999999 milliseconds

    So for loop is undeniably faster – by at least 22% of the closest ToDictionary implementation. I’ve tried it with 100,000 elements and it gets up to about 30% then.

    Note the second for loop result – seems to suggest that bypassing the Length property is a good idea. Indeed I’ve done 4 runs in a row and these are the results (including the first, from above):

    For loop: 0.28880804, 0.28562478, 0.283770739999999, 0.287241679999999

    For loop(2): 0.2773845, 0.27621306, 0.27869996, 0.27962916

    ToDictionary: 0.479094339999998, 0.476417939999997, 0.476162219999997, 0.475776479999997

    Hybrid: 0.353655779999999, 0.3583224, 0.352022739999998, 0.349865779999999

    However I have seen the results flip for at least one benchmark result, too – demonstrating how largely pointless this kind of benchmarking can be. Realistically we should be generating a different array for each test, too, to avoid caching etc.

    There is an alternative.

    If the method you’re calling accepts an IDictionary<int, string> (note – the interface); and not a Dictionary<int, string> you can create a simple wrapper type that implements the necessary members of the interface, thus sidestepping the need to project into a Dictionary at all; so long as only certain members are required. Here’s an almost complete implementation:

    public class FakeDictionary : IDictionary<int, string>
    {
        private readonly string[] _array;
    
        public FakeDictionary(string[] array)
        {
            _array = array;
        }
    
        #region IDictionary<int,string> Members
    
        public void Add(int key, string value)
        {
            throw new NotSupportedException();
        }
    
        public bool ContainsKey(int key)
        {
            return key >= 0 && key < _array.Length;
        }
    
        public ICollection<int> Keys
        {
            get { return Enumerable.Range(0, _array.Length).ToArray(); }
        }
    
        public bool Remove(int key)
        {
            throw new NotSupportedException();
        }
    
        public bool TryGetValue(int key, out string value)
        {
            value = null;
            if (key >= 0 && key < _array.Length)
            {
                value = _array[key];
                return true;
            }
            return false;
        }
    
        public ICollection<string> Values
        {
            get { return _array; }
        }
    
        public string this[int key]
        {
            get
            {
                try
                {
                    return _array[key];
                }
                catch (ArgumentOutOfRangeException ex)
                {
                    throw new KeyNotFoundException("Invalid key", ex);
                }
            }
            set //note - can't be used to add items
            {
                try
                {
                    _array[key] = value;
                }
                catch (ArgumentOutOfRangeException ex)
                {
                    throw new KeyNotFoundException("Invalid key", ex);
                }
            }
        }
    
        #endregion
    
        #region ICollection<KeyValuePair<int,string>> Members
    
        public void Add(KeyValuePair<int, string> item)
        {
            throw new NotSupportedException();
        }
    
        public void Clear()
        {
            throw new NotSupportedException();
        }
    
        public bool Contains(KeyValuePair<int, string> item)
        {
            return ContainsKey(item.Key) && _array[item.Key].Equals(item.Value);
        }
    
        public void CopyTo(KeyValuePair<int, string>[] array, int arrayIndex)
        {
            //too much for an SO answer.
            throw new NotImplementedException();
        }
    
        public int Count
        {
            get { return _array.Length; }
        }
    
        public bool IsReadOnly
        {
            //technically it's not - because we can modify individual elements - 
            //but at the collection-level it is
            get { return true; }
        }
    
        public bool Remove(KeyValuePair<int, string> item)
        {
            throw new NotSupportedException();
        }
    
        #endregion
    
        #region IEnumerable<KeyValuePair<int,string>> Members
    
        public IEnumerator<KeyValuePair<int, string>> GetEnumerator()
        {
            throw new NotImplementedException();
        }
    
        #endregion
    
        #region IEnumerable Members
    
        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {
            throw new NotImplementedException();
        }
    
        #endregion
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

All, I have a string in a dictionary that's in an array that I
I have array of strings, String[] data and it's 10 elements has value P
I have an array of strings plus one additional string. I want to use
I have a an array of strings:e.g: string [] names ={P,A,B,G,F,K,R} I have another
I have a string array: string[] authors = new string[3]; authors[0] = Charles Dickens;
I have an array of dictionary words and a random string like twowords What
I have a dictionary myResult: Dictionary<String^,array< Byte >^>^ myResult = gcnew Dictionary<String^,array< Byte >^>();
I have an array like this - string[] input = new string[] {bRad, Charles,
I have a string array of 3 different command line commands. Instead of writing
I have a string array in C# and I intend to copy it in

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.