【问题标题】:Extract grouped data from dataset从数据集中提取分组数据
【发布时间】:2014-07-30 15:05:07
【问题描述】:

国家数据:

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 ;
}

输出应该是这样的

List countryData=new List();

this countryData 应该包含这样的数据(预期结果)

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

我尝试按数据集进行分组,但是,我没有得到如上预期的结果:

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

这应该如何分组/任何其他方法?提前致谢。

【问题讨论】:

    标签: c# asp.net .net vb.net dataset


    【解决方案1】:

    您可以在 foreach 语句中手动实现这一点,它可能有点复杂,但它为您提供了您想要的相同结构:

                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 字典。

    【讨论】:

      猜你喜欢
      • 2011-04-18
      • 2020-06-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-11
      • 2019-09-02
      • 2014-07-05
      相关资源
      最近更新 更多