2014-12-08 2 views
1

의 번호를 반복 나는 다음과 같은 사전이 있습니다사전 항목

Dictionary<string, List<string>> myList = new Dictionary<string,List<string>>(); 

이 사전이 채워 도착, 나는 결코 내가 가지고 얼마나 많은 항목을 알고 않을거야합니다.

출력 예 : 사전의 요소 : (키, 값)

{"Code",{"Test1", "Test2", "Test3"}} 

{"Desc",{"Desc1", "Desc2", "Desc3"}} 

{"Name",{"name1", "name2", "name3"}} 

어떻게 모든 사전을 통해 내가 루프 인덱스를 얻을 것이다

무엇인가를, 즉 값을 얻을 - >

{Code = "Test1", Desc = "desc", Name = "name1"} 
{Code = "Test2", Desc = "desc2", Name = "name2"} 
{Code = "Test3", Desc = "desc3", Name = "name3"} 

아이디어가 있으십니까?

감사

+1

를? – Sajeetharan

+0

튜플을 사용해야하는 이유는 무엇입니까? 사전에서 항상 값을 복제하는 경우 첫 번째 매개 변수를 사용하는 것은 무엇입니까? –

+0

나는 그것에 대응하는 수업도있다. 터플은 제가 전에 시도한 문자열이었습니다. 이것은 변경할 수 있습니다. – tau

답변

1

의 핵심은 데이터의 각 열 대신의를 제공 할 것입니다 사전 열거 등의 각 행에 대한 배열의 집합을 구축하는 것입니다. 이는 Aggregate 확장 메소드와 간단한 Select 문을 사용하여 수행 할 수 있습니다. 이 경우

// Assuming the following class as a destination type 
class Foo 
{ 
    public Foo(string[] values) 
    { 
     Code = values[0]; 
     Name = values[1]; 
     Desc = values[2]; 
    } 

    public string Code; 
    public string Name; 
    public string Desc; 
} 

// This would be the code required to parse the data 
var destination = dataSource["Code"].Aggregate(new List<Foo>(), (entries, _) => 
{ 
    var curentRow = entries.Count(); 

    var entryData = dataSource.Select(property => property.Value[curentRow]).ToArray(); 

    entries.Add(new Foo(entryData)); 

    return entries; 
}); 

, 우리는 데이터 소스 (사용자 사전)에 얼마나 많은 항목을 파악하는 열쇠로 Code 속성을 사용합니다. 사전에 값이 누락 된 행 (코드 행보다 적은 항목)이 있으면이 코드는 모든 행에 같은 양의 항목이 있다고 가정하므로 실패합니다.

이 경우 Aggregate 메서드는 for 루프와 비슷하게 작동하며 나중에 데이터의 특정 항목에 액세스 할 때 사용하는 currentRow이라는 기본 카운터를 제공합니다. 이 카운터는 우리가 List<Foo>에 저장 한 항목의 양입니다. 0에서 시작하여 결과 세트에 새 값을 추가 할 때마다 증가합니다.

다음 단계는 데이터 소스의 모든 항목을보고 현재 행과 일치하는 값에 액세스하는 것입니다. 그런 다음이를 배열로 변환하고이 데이터를 deserialize하는 방법을 알고있는 대상 유형의 생성자로 전달합니다.

-1

은 잘못된 데이터 구조처럼 보입니다. 임의의 속성 집합을 가진 객체 세트가있는 것처럼 보입니다. 당신은

"item1"->code:'code1",desc:"desc1".... 
"item2"->code:'code2",desc:"desc2", color:"red", size:'42" 

map<string,map<string,string>>이 ......

0

이 완벽하게 문제를 해결하는 기본 솔루션이 필요합니다. "Code", "Desc"...로 foreach 루프를 증가시킬 수 있도록 IEnumerable 객체를 만들었습니다.

문자열 (사전 키)을 얻으면 사전의 각 키 값인 목록을 검토 할 수 있습니다. 아래의 코드 Dictionary에있는 모든 요소를 ​​작성하고 계산하며 각 값에 대해 List의 모든 요소를 ​​씁니다.

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 

namespace ConsoleApplication1 
{ 
    class Program 
    { 
     public static IEnumerable<string> Helper() // Neccessary to use in foreach loop 
     { 
      yield return "Code"; 
      yield return "Desc"; 
      yield break; 
     } 
     static void Main(string[] args) 
     { 
      Dictionary<string, List<string>> container = new Dictionary<string, List<string>>(); 
      List<string> l1 = new List<string>(); 
      List<string> l2 = new List<string>(); 

      l1.Add("l1s1"); 
      l1.Add("l1s2"); 
      l1.Add("l1s3"); 

      l2.Add("l2s1"); 
      l2.Add("l2s2"); 
      l2.Add("l2s3"); 

      container.Add("Code", l1); 
      container.Add("Desc", l2); 

      int count = 0; 
      foreach (string k in Helper()) // get all Keys 
      { 
       for (int i = 0; i < container[k].Count; i++) 
       { 
        Console.WriteLine(container[k][i].ToString()); // Write each element in list 
        count++; 
       } 
       Console.WriteLine(); 
      } 
      Console.WriteLine(count.ToString()); 
     } 
    } 
} 

각 목록에 몇 개의 요소가 있는지 알 필요가 없습니다.출력은 같다 :

enter image description here

또는 도우미를 만들지 않고()는 아래와 같이 할 수있다 : 당신의 이름과 항목을 대응하는지도 어떻게

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 

namespace ConsoleApplication1 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      Dictionary<string, List<string>> container = new Dictionary<string, List<string>>(); 
      List<string> l1 = new List<string>(); 
      List<string> l2 = new List<string>(); 

      l1.Add("l1s1"); 
      l1.Add("l1s2"); 
      l1.Add("l1s3"); 

      l2.Add("l2s1"); 
      l2.Add("l2s2"); 
      l2.Add("l2s3"); 

      container.Add("Code", l1); 
      container.Add("Desc", l2); 

      int count = 0; 
      foreach (string k in new string [] {"Code","Desc"}) // get all Keys 
      { 
       for (int i = 0; i < container[k].Count; i++) 
       { 
        Console.WriteLine(container[k][i].ToString()); // Write each element in list 
        count++; 
       } 
       Console.WriteLine(); 
      } 
      Console.WriteLine(count.ToString()); 
     } 
    } 
} 
+1

그것은 'yield'의 다소 이상한 사용입니다. 당신은 단순히 foreach (문자열 k in new [] Code ","Desc "})를 대신 할 수 있습니다. – Blorgbeard

+0

그게 맞습니다. 통지 해 주셔서 감사합니다. –