2012-08-17 34 views
10

文字列のリストではなく、設定にStringCollectionしか格納できないため、上記の機能が必要です。リストを<string>をStringCollectionに変換

ListをStringCollectionに変換するにはどうすればよいですか?バック変換

StringCollection collection = new StringCollection(); 
foreach (string element in list) 
{ 
    collection.Add(element); 
} 

は、LINQで簡単です::また

StringCollection collection = new StringCollection(); 
collection.AddRange(list.ToArray()); 

、中間配列を避けること(ただし、おそらくより多くの再配分を含む):

List<string> list = collection.Cast<string>().ToList(); 

答えて

23

List.ToArray()これはListを配列に変換し、値を追加するために使用できます。あなたのStringCollection

StringCollection sc = new StringCollection(); 
sc.AddRange(mylist.ToArray()); 

//use sc here. 

読むthis

+0

ただ、なぜ推奨する中間配列を避けるだろう、不思議? – l46kok

+1

@ l46kok:他のものはすべて同じで、余分な中間コピーを避けることが常に推奨されます。しかし、この場合、どのようなアプローチがより効率的か(余分な再割り当てのため)、設定のコレクションの典型的なサイズを考えると、おそらく重要ではないことは明らかではありません。 –

+0

@MarceloCantos:いつも?私はそれと一緒に行かないだろう。最初のコードははっきりとシンプルであり、おそらくそれほど重要ではないとすれば、おそらく効率的ではないがもっと明白なアプローチに固執します。 –

1

使用方法について

+2

'sc.AddRange(mylist.ToArray());'のように 'string [] str = mylist.ToArray();'を実行しているのはなぜですか? – dtsg

+2

@john: 'mylist.ToArray()'が返すものと 'AddRange()'が返すものを教えてください。 –

+2

'.ToArray();'を使うとそれは明白ではありませんか? – dtsg

0

ここStringCollectionIEnumerable<string>を変換する拡張メソッドです。それは他の答えと同じように動作し、ちょうどそれを包みます。

public static class IEnumerableStringExtensions 
{ 
    public static StringCollection ToStringCollection(this IEnumerable<string> strings) 
    { 
     var stringCollection = new StringCollection(); 
     foreach (string s in strings) 
      stringCollection.Add(s); 
     return stringCollection; 
    } 
} 
0

私が希望:

Collection<string> collection = new Collection<string>(theList); 
関連する問題