2016-03-23 9 views
1

私はDictionary<Document, File[ n ]> のように私はその辞書)(<KeyValuePair <ドキュメント、ファイル>>一覧に階層辞書を変換し

現在、私はforeachのを使用しているフラットなシステムですList<KeyValuePair<Document, File>> に変換したいされた辞書を持っていますそのリストを変換することは可能ですか? Linqを使用して、事前

+0

'foreach' - >' SELECT'。 'foreach foreach' - >' SelectMany' –

+1

なぜLinqを使いたいのですか?あなたのコードに何か問題がありますか?大規模な/巨大なデータストレージのためのシンプルなループははるかに高速Linqソリューションです。 –

+0

@MaciejLosコードは完全に動作しているだけです。コード行を減らすためにLinqで変換してください。 –

答えて

3

 var documentFileList = RepositoryFactory.FileRepository.GetFiles(_case); 

    var retVal = new List<KeyValuePair<Document, File>>(); 
    if (documentFileList != null) 
    { 
    foreach (var docFileKeyPair in documentFileList) 
    { 
     if (docFileKeyPair.Value != null) 
     { 
     foreach (var fileEntity in docFileKeyPair.Value) 
     { 
      var document = docFileKeyPair.Key as Document; 
      if (document != null) 
      { 
      retVal.Add(new KeyValuePair<Document, File>(document, fileEntity)); 
      } 
     } 
     } 
    } 
    } 

おかげで、あなたはこれを行うことができます。

var flattenList = documentFileList.SelectMany(x=>x.Value.Where(v=> v != null).Select(s=> new KeyValuePair<Document, File>(x.Key, s))) 
            .ToList(); 

チェックこのexample code

+0

OPコードから 'null'チェックを入れるのはどうですか? –

+0

@IvanStoev素敵なキャッチ、私は私の答えを更新しました。 –

+0

ありがとう@HariPrasad –

関連する問題