[英]Arrays, multi-dimensional and jagged…in C#
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,arraylist列表,但都無濟於事,我的代碼失敗了,但從理論上講我知道我想做什么。
我個人將使用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];
聽起來您根本根本不需要數組-您想要一個每個條目具有多個值的字典。 如果您可以使用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 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.