2014-06-10 6 views
-1

CountryData : I 데이터 집합이 데이터를추출 그룹화 된 데이터

Keyid Data1  Data2 

200 London  UK 
200 Paris  France 
200 Vancouver Canada 
201 NYC   US 

, 전을 반복하려면 상기 출력

같아야

Class CountryData 
{ 

int keyid; 
public struct MyData() 
    {string data1, string data2 } 

public MyData Data ; 
} 

같은 클래스 객체를 형성 할

목록 countryData = new List();

그러나, 나는 위와 같이 예상 된 결과를 얻을하지 않습니다, 나는 데이터 세트로 그룹에 시도

countryData[0] 
      -keyid - 200  
      Data[0].Data1 - London 
      Data[0].Data2 - UK 

      Data[1].Data1 - Paris 
      Data[1].Data2 - France 

      Data[2].Data1 - Vancouver 
      Data[2].Data2 - Canada 

countryData[1] 
      -keyid -201  

      Data[0].Data1 - NYC 
      Data[0].Data2 - US 

이 (예상 결과) 등의 데이터를 보유해야이 countryData :

DataTable dt = ds.Tables[0].AsEnumerable() 
        .GroupBy(r => r["keyid"]) 
        .Select(y=>y.FirstOrDefault()).CopyToDataTable(); 

이것이 다른 접근법에 어떻게 분류되어야 하는가? 미리 감사드립니다.

당신은 foreach 문에서 수동으로 달성 할 수

답변

0

, 그것은 조금 복잡 할 수도 있지만 그것은 당신에게 당신이 원하는 동일한 구조 제공 :

  var myMainData = new Dictionary<int, List<Dictionary<string, string>>>(); 
      var myDataValue = new List<Dictionary<string, string>>(); 
      var values = new Dictionary<string, string>(); 

      //get the first key once 
      int lastKeyId = Convert.ToInt32(dataSet.Tables["CountryData"].Rows[0]["Keyid"]); 

      foreach (DataRow row in dataSet.Tables["CountryData"].Rows) 
      { 
       int key = Convert.ToInt32(row["Keyid"]); 
       if (lastKeyId != key) 
       { 
        myMainData.Add(key, myDataValue); //add this to the dictionary 
        myDataValue.Clear(); //clear previous list value 
        values.Clear(); //clear previous values 
       } 

       //add new values 
       values.Add(row["Data1"].ToString(), row["Data2"].ToString()); 
       myDataValue.Add(values); 

       lastKeyId = key; //set the current key 
      } 

지금 당신은 당신의 코드에서 어디 myMainData 사전을 사용할 수 있습니다.