c# - C#如何循环遍历列表的所有元素
问题描述
我有以下问题。我有一个字符串列表,想拆分这些。之后,我想给每个对象元素一个对列表项的引用。
例子:
List<string> valueList = attr.Split(' ').ToList<string>();
这个列表有这样的项目:
name,string,age,int
对于此示例,每个对象都需要获取 2 条信息,首先是名称(例如:“name”或“age”),其次是类型(例如:“string”、“int”)。
现在我想得到一个包含这些信息的对象。所以我创建了对象并将这些对象放入一个列表中。
例子:
List<MyObject> listObjects = new List<MyObject>();
for (int i = 0; i < ValueList.Count; i++)
{
MyObject object = new MyObject();
if (ValueList.Any(s => s.StartsWith(modifier)) == true)
{
object.name = ValueList[i];
object.type = ValueList[i + 1];
}
listObjects.Add(object);
}
但是通过我的解决方案,我得到了System.ArgumentOutOfRangeException。我对此的解释是 foreach 但我不知道如何获取字符串列表中的每个项目并将它们添加到对象的技术。还有一个问题是 List 的 1 项应该有 2 个元素(名称、类型),但是使用我的方法,我将遍历每个元素的foreach。在 C# .Net Framework 中有没有更好的方法来做到这一点?
解决方案
我想你想要这样的东西。
// Store your relevant keywords in a list of strings
List<string> datatypes = new List<string>{"string", "int"};
// Now loop over the ValueList using a normal for loop
// starting from the second elemend and skipping the next
for(int x = 1; x < ValueList.Count; x+=2)
{
// Get the current element in the ValueList
string current = ValueList[x];
// Verify if it is present in the identifiers list
if (datatypes.Contains(current)))
{
// Yes, then add the element before the current and the current to the MyObject list
MyObject obj = new MyObject;
obj.name = ValueList[x - 1];
obj.type = current;
listObjects.Add(obj);
}
}
推荐阅读
- random-forest - 需要帮助让方法 = cforest 在插入符的 train() 中工作,使用留一出交叉验证
- list - 如何在 F# 中打印记录中的类型总和?
- asp.net - 无法跟踪实体类型“产品”的实例,因为已经在跟踪具有相同键值 {'Id'} 的另一个实例
- angular - 无法绑定到“设置”,因为它不是“angular2-multiselect”的已知属性
- html - 如何使我的网站主页在所有屏幕上看起来都一样
- swiftui - 为什么视图比屏幕更宽?
- python - numpy.histogram2d 生成的相图上的 K 均值聚类
- python - Word如何在指定字符串下插入表格?
- reactjs - 以编程方式启动 React Draggable 拖动
- julia - 如何指定我的模型应该在 Flux.jl 中训练的纪元数