C# 从数据集中提取分组数据
国家数据:C# 从数据集中提取分组数据,c#,asp.net,.net,vb.net,dataset,C#,Asp.net,.net,Vb.net,Dataset,国家数据: 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 My
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=新列表()
此countryData应包含如下数据(预期结果)
我尝试按数据集分组,但没有得到上述预期结果:
DataTable dt = ds.Tables[0].AsEnumerable()
.GroupBy(r => r["keyid"])
.Select(y=>y.FirstOrDefault()).CopyToDataTable();
应如何将其归类为/任何其他方法?提前感谢。您可以在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
}
var myMainData=newdictionary();
var myDataValue=新列表();
var值=新字典();
//拿到第一把钥匙一次
int lastKeyId=Convert.ToInt32(dataSet.Tables[“CountryData”]。行[0][“Keyid”);
foreach(dataSet.Tables[“CountryData”].Rows中的DataRow行)
{
int key=Convert.ToInt32(行[“Keyid]”);
if(lastKeyId!=密钥)
{
myMainData.Add(key,myDataValue);//将其添加到字典中
myDataValue.Clear();//清除以前的列表值
values.Clear();//清除以前的值
}
//添加新值
Add(第[“Data1”].ToString()行,第[“Data2”].ToString()行);
添加(值);
lastKeyId=key;//设置当前密钥
}
现在,您可以在代码中的任何位置使用myMainData字典
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
}