【发布时间】:2018-01-19 07:43:12
【问题描述】:
我有一组数据存储在一个数据库表中,我想将它们转换成一个组结构列表,每个组都包含数据数组。
我可以使用相当长的方法来做到这一点。我想知道是否有更紧凑的方法来实现这一目标?我怀疑 Linq 应该非常适合这种操作,但我真的不知道如何开始。
以下示例说明了我目前正在做的事情。我的真实数据更复杂。
数据将存储在这样的结构中
public struct GroupData
{
private string aString;
private int anInt;
public GroupData(string aString, int anInt)
{
this.aString = aString;
this.anInt = anInt;
}
}
这又要存储在一个组结构中
public struct Group
{
private string groupId;
private GroupData[] groupData;
public Group(string groupId, GroupData[] groupData)
{
this.groupId = groupId;
this.groupData = groupData;
}
}
我目前正在这样做
//Create some dummy data
DataTable table = new DataTable();
table.Columns.Add("GROUP_ID", typeof(string));
table.Columns.Add("A_STRING", typeof(string));
table.Columns.Add("AN_INT", typeof(int));
table.Rows.Add("A", "this_is_A2", 7);
table.Rows.Add("A", "this_is_A2", 4);
table.Rows.Add("B", "this_is_B1", 3);
table.Rows.Add("C", "this_is_C1", 1);
table.Rows.Add("D", "this_is_D1", 3);
table.Rows.Add("D", "this_is_D2", 2);
//Create list of groups with arrays of groupdata
string theString, theGroupId;
int theInt;
List<Group> theGroups = new List<Group>();
List<GroupData> groupDataList;
Dictionary<string, List<GroupData>> groupDataDict = new Dictionary<string, List<GroupData>>();
//Read all rows and convert to structs
for (int i = 0; i < table.Rows.Count; i++)
{
theGroupId = (string)table.Rows[i]["GROUP_ID"];
theString = (string)table.Rows[i]["A_STRING"];
theInt = (int)table.Rows[i]["AN_INT"];
//Collect all GroupData into their respective Groups
if (!groupDataDict.TryGetValue(theGroupId, out groupDataList))
{
groupDataList = new List<GroupData>();
groupDataDict.Add(theGroupId, groupDataList);
}
groupDataList.Add(new GroupData(theString, theInt));
}
//Insert each group into the list
foreach (KeyValuePair<string, List<GroupData>> kv in groupDataDict)
theGroups.Add(new Group(kv.Key, kv.Value.ToArray()));
我看到我的问题与这篇文章Group by in LINQ 密切相关,我想我可以先将我的数据表转换为列表,然后使用规定的方法。但理想情况下,我想绕过先转换为列表的步骤,直接对DataTable进行操作。
【问题讨论】: