Most elegant way to convert string array into a dictionary of strings

后端 未结 8 1031
没有蜡笔的小新
没有蜡笔的小新 2020-12-08 18:39

Is there a built-in function for converting a string array into a dictionary of strings or do you need to do a loop here?

8条回答
  •  盖世英雄少女心
    2020-12-08 19:25

    Assuming you're using .NET 3.5, you can turn any sequence (i.e. IEnumerable) 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(listOfStrings);
    

提交回复
热议问题