首页 > 解决方案 > 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 中有没有更好的方法来做到这一点?

标签: c#stringlistobjectforeach

解决方案


我想你想要这样的东西。

// 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);
    }
}

推荐阅读