我有一个包含2个元素的数组,每个元素可以包含一个或多个object
,其中包含两个属性:Id
- > (string
)和Names
- &gt; (List<string>
)。
如何循环浏览第二个对象的元素并获取每个元素的Id
和Names
属性?
这就是我尝试实施它的方式,但不起作用:
foreach (var elem in classArray[1].GetType().GetProperties())
{
var id = elem.Id;
var name = elem.Names;
}
这是Classification
类:
public class Classification
{
public string Id { get; set; }
public List<string> Names { get; set; }
}
这是我的代码:
List<object> classCollection = new List<object>();
dynamic response = JsonConvert.DeserializeObject(result);
for (int i = 0; i < response.Count; i++)
{
var classObj = response[i].element_classifications;
var className = new List<string>();
List<Classification> classList = new List<Classification>();
for (int k = 0; k < classObj.Count; k++)
{
var classification = classObj[k].classifications;
for (int j = 0; j < classification.Count; j++)
{
className.Add(classification[j].name.Value);
}
classList.Add(new Classification { Id = classObj[k].id.Value, Names = className });
}
classCollection.Add(classList);
}
var classArray = classCollection.ToArray();
答案 0 :(得分:2)
您可以将对象强制转换为适当的类:
foreach (var elem in ((IEnumerable)classArray[1]).Cast<ExcelSDRAddIn.UserControlSDR.Classification>())
{
var id = elem.Id;
var name = elem.Names;
}
答案 1 :(得分:0)
如果对象始终相同
dynamic v = classArray[i].Id;
dynamic name = classArray[i].Names;
或者您可以使用dynamic或var
pythonlinkvalidator
答案 2 :(得分:0)
从您的图片来看,它看起来会起作用:
foreach(var item in classArray[1])
{
var typedItem = (ExcelSDRAddIn.UserControlSDR.Classification) item;
Console.WriteLine($"Id {typedItem.Id} has names:");
for (int i = 0; i < typedItem.Names.Count; i++)
{
Console.WriteLine($" - {typedItem.Names[i]}");
}
}