How can I transform a List <string> to a Dictionary<string, int>?
This should be number from zero to n.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
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.
You can use
ToDictionary()to create aDictionaryfrom anyIEnumerable.The lambda passed to
ToDictionaryis thekeySelector. Usually you use this to select a property from the items in theIEnumerableto be the key, but here, we use it to provide a count.Edit: The second version uses two selectors. The first is the key. By providing a
x => xlambda, we are just using the string that came from the list. The second selector is the value. Here, we are providing the counter,i.Performance
I decided to test out the performance of my method versus pst’s method.
Test Code:
Output:
Output (After question edit):
In conclusion, it appears that there is a roughly 40% improvement by using a counter instead of creating the intermediate, anonymous-typed objects.