我有一个包含字符串的数组,我想解析它来制作每组4个字符串的对象。这可以通过for循环完成吗?
唯一标识组的是每个组将包含4个字符串。
数组看起来像这样,其中顶部值“NumberOfItemsInArray”将是一个数字,表示后面有多少个项目组。项目数量是动态的。
NumberOfItemsInArray
Item1-Name
Item1-Price
Item1-DiscountRate
Item1-Category
Item2-Name
Item2-Price
Item2-DiscountRate
Item2-Category
有没有办法干净利落地做到这一点?
答案 0 :(得分:2)
假设你有一些构造函数用于获取4个字符串(a,b,c,d)的YourObject,它应该相当简单,给定输入字符串数组,MyArray和输出List<YourObject>
YourObjectList:< / p>
int iItems = System.Convert.ToInt32(MyArray[0]);
for (int i = 0; i < iItems; i+=4)
YourObjectList.Add( new YourObject( MyArray[i+1], MyArray[i+2], MyArray[i+3], MyArray[i+4] ) );
这应该是正确的 - 虽然通过编译器运行它 - 约翰
答案 1 :(得分:0)
根据数组的长度确定四个组的数量。然后只需遍历原始数组,并填充四个数组的数组。
string[] itemsArray = { "8", "a", "b", "c", "d", "e", "f", "g", "h" };
int nGroups = (itemsArray.Length - 1) / 4;
string[][] groups = new string[nGroups][];
for (int i = 0; i < nGroups; i++) {
print("- new group of four -");
groups[i] = new string[4];
for (int j = 0; j < 4; j++) {
groups[i][j] = itemsArray[i * 4 + j + 1];
print(groups[i][j]);
}
}
输出:
- new group of four -
a
b
c
d
- new group of four -
e
f
g
h
答案 2 :(得分:0)
Array.Lenght
看起来很无用,因为你有using System;
using System.Collections.Generic;
namespace Program {
class _Main {
// Initialize dictionary with values
static Dictionary<string, string> dictionaryWithStrings = new Dictionary<string, string> {
{ "NumberOfItemsInArray", "2" },
{ "Item1-Name", "Some name" },
{ "Item1-Price", "0.5$" },
{ "Item1-DiscountRate", "?%" },
{ "Item1-Category", "Some category" },
{ "Item2-Name", "Other name" },
{ "Item2-Price", "4$" },
{ "Item2-DiscountRate", "24%" },
{ "Item2-Category", "Other category" }
};
// Create *dynamic* list with Item's
static List<Item> objects = new List<Item>();
static void Main() {
// "- 1" removes the NumberOfItemsInArray from count
// "/ 4" Since you have always 4 strings
for (int i = 1; i <= (dictionaryWithStrings.Count - 1) / 4; i++) {
objects.Add(new Item {
Name = dictionaryWithStrings["Item"+i+"-Name"],
Price = dictionaryWithStrings["Item"+i+"-Price"],
DiscountRate = dictionaryWithStrings["Item"+i+"-DiscountRate"],
Category = dictionaryWithStrings["Item"+i+"-Category"]
});
}
Console.WriteLine("objects contains [" + objects.Count + "] items, values:");
foreach (Item item in objects) {
Console.WriteLine("Item id: [" + objects.IndexOf(item) +
"], Name: [" + item.Name +
"], Price: [" + item.Price +
"], DiscountRate: [" + item.DiscountRate +
"], Category: [" +item.Category + "]"
);
}
}
struct Item {
public string Name;
public string Price;
public string DiscountRate;
public string Category;
}
}
}
,我认为你的数组不是数组,我认为它是字典,如果有的话那么看看这个:
{{1}}