阵列,多维和锯齿状......在C#中

时间:2011-02-23 17:44:39

标签: c# arrays multidimensional-array

C#到ASP.Net 2.0。

在数据表中,我有两列ID,attributeId和productAttributeID。

我想循环遍历此表并以这样的方式对它们进行“分组”:productAttributeIds具有与之关联的一个或多个attributeIds。

例如,在伪代码中,这就是我正在做的事情

For each datarow in myDatatable.rows

Insert into myarray at index(productattributeId) - corresponding attributeId

end foreach

所以这将循环,每次出现相同的productAttributeId时,attributeId将被添加到相应的数组中。

显然这不起作用,因为数组需要声明大小等等。

我已经尝试过多维数组,锯齿状数组,arraylists,arraylists列表都无济于事,我的代码失败但我在理论上知道我想做什么。

2 个答案:

答案 0 :(得分:4)

我个人会使用Dictionary<int, List<int>>

foreach(var row in data)
{
    // Get your data...
    int attributeId = GetAttributeId();
    int productAttributeId = GetProductAttributeId();

    List<int> attributes;
    if(!dictionary.TryGetValue(productAttributeId, out attributes)
    {
       attributes = new List<int>();
       dictionary[productAttributeId] = attributes;
    }
    attributes.Add(attributeId);
}

然后,您可以轻松获取属性的所有产品属性:

List<int> attributeIds = dictionary[productAttributeId];

答案 1 :(得分:4)

听起来你根本不想要一个数组 - 你想要一个每个条目有多个值的字典。如果您可以使用LINQ,那正是ToLookup为您所做的。类似的东西:

var lookup = dataTable.AsEnumerable()
                      .ToLookup(row => row.Field<int>("ProductAttributeId"),
                                row => row.Field<int>("AttributesId"));

然后您可以执行以下操作:

foreach (int attributeId in lookup[5])
{
   ...
}

当然,您必须拥有.NET 3.5,或者如果您使用的是.NET 2.0,则可以使用LINQBridge

相关问题