【问题标题】:C# how can I loop through all Elements of a List <string>C#如何遍历列表<string>的所有元素
【发布时间】:2020-04-14 07:45:45
【问题描述】:

我有以下问题。我有一个字符串列表,想拆分这些。之后,我想给每个对象元素一个对列表项的引用。

例子:

List<string> valueList = attr.Split(' ').ToList<string>();

这个列表有这样的项目:

name,string,age,int

对于这个例子,每个 Object 需要获取 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 中有没有更好的方法?

【问题讨论】:

  • 您在空格上拆分,但您的初始输入用逗号分隔
  • 这是一个例子,所以我的意思是拆分后 List 元素可能看起来像这样。
  • 也不清楚 readerValueArray 是什么以及它包含多少元素。这可能是您的 IndexOutOfRangeException 的原因
  • @brstkr 如果您真的想得到帮助,您应该帮助我们了解您的问题。不暴露问题的相关部分并不是很有用。请阅读minimal reproducible example
  • edit您的问题,这样它实际上显示了您遇到的问题,因为您发布的内容没有。

标签: c# string list object foreach


【解决方案1】:

我想你想要这样的东西。

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

【讨论】:

  • 谢谢!它帮助了我很多,但我有一个问题。所以当我要像这样循环时,它只会创建一个对象而不是两个(名称=“名称”和类型=“字符串”的对象)。我该如何解决这个问题,是因为 valueList.Count 条件吗?
  • 您确定在最后一个字符串 (int) 之后没有空格或其他空白字符吗?将此行更改为 string current = ValueList[x].Trim(); 也包含区分大小写(字符串不等于字符串)
  • 好的,我将它添加到 string current 但最后一个字符串之后没有空格。它成功创建了第一个对象(使用正确的元素),但没有创建第二个对象。
  • 不确定问题出在哪里。我用您的示例输入(“名称,字符串,年龄,int”)尝试了这段代码,一切都按预期工作。我建议你使用调试器,一步一步检查你的代码流和所涉及的变量的值
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-12-10
  • 2019-04-15
  • 1970-01-01
  • 2018-09-05
  • 1970-01-01
  • 2015-02-14
  • 1970-01-01
相关资源
最近更新 更多