views:

777

answers:

4

is there a built in function for this or do you need to do a loop here.

+3  A: 

What do you mean?

A dictionary is a hash, where keys map to values.

What are your keys and what are your values?

foreach(var entry in myStringArray)
    myDictionary.Add(????, entry);
Andrew Bullock
+9  A: 

Assuming you're using .NET 3.5, you can turn any sequence (i.e. IEnumerable<T>) into a dictionary:

var dictionary = sequence.ToDictionary(item => item.Key,
                                       item => item.Value)

where Key and Value are the appropriate properties you want to act as the key and value. You can specify just one projection which is used for the key, if the item itself is the value you want.

So for example, if you wanted to map the upper case version of each string to the original, you could use:

var dictionary = strings.ToDictionary(x => x.ToUpper());

In your case, what do you want the keys and values to be?

If you actually just want a set (which you can check to see if it contains a particular string, for example), you can use:

var words = new HashSet<string>(listOfStrings);
Jon Skeet
That risc is always there, unless you check before for duplicate keys.
Dykam
@Dykam: Indeed. If you want to handle duplicates, you potentially want `ToLookup` instead. Hopefully we'll find out more if the OP explains what they're really trying to do.
Jon Skeet
+3  A: 

You can use LINQ to do this, but the question that Andrew asks should be answered first (what are your keys and values):

using System.Linq;

string[] myArray = new[] { "A", "B", "C" };
myArray.ToDictionary(key => key, value => value);

The result is a dictionary like this:

A -> A
B -> B
C -> C
Ronald Wildenberg
+2  A: 

If you need a dictionary without values, you might need a HashSet:

var hashset = new HashSet<string>(stringsArray);
Kobi