【问题标题】:Loop List of List string with a condition the same order on the extraction C#提取C#中条件相同的List字符串的循环列表
【发布时间】:2020-03-28 07:00:47
【问题描述】:

我有一个列表字符串列表:

  List<List<string>> donnees = new List<List<string>>();

我的目标是提取一个 XElement 列表,然后 XElement 验证一个条件: 我希望每一行都包含每个列表的值,并且所有值都必须是相同的顺序

以这个列表为例

   donnees : { { "a","b","c","d"}, {"1", "2", "3", "4"}, { "first", "second", "third", "fourth"} }

我想得到这样的列表值:

<value> "a", "1", "first" </value>
<value> "b", "2", "second" </value>
<value> "b", "3", "third" </value>
<value> "d", "4", "fourth" </value>

(其实是:获取每个列表的所有值的相同顺序)

当然,我有一个很大的列表,

我用这个测试

foreach (List<string> list in donnees)
{
foreach (string s in list)
{
  //Here to get the XElement with the values 
  //It is OK
}
}

但这不是目的, 那么我该如何解决呢?谢谢,

【问题讨论】:

  • 我们是否假设每个列表具有相同的元素。如果是这样就用for循环,根据第一个内部列表的元素个数,然后用索引获取每个列表中的值
  • /\和元素个数一样?
  • 还有,你得到的结果是什么?使用相同的示例数据,你能告诉我们你的结果是什么吗?
  • 谢谢大家,@Anu Viswan 找到解决方案

标签: c# list for-loop foreach


【解决方案1】:

您实际上是在尝试按列读取列表列表,然后组合结果。您可以使用嵌套循环来执行此操作。

以下方法应该可以帮助您创建所需的 XElement 集合

public static IEnumerable<XElement> GetList(List<List<string>> source)
{
    var maxIndex= source.Max(x=>x.Count());
    var index = 0;

    while(index<maxIndex)
    {
        var lineList = new List<string>();
        foreach(var list in source.Select(x=>x))
        {
            if(list.Count > index)
                lineList.Add($"\"{list[index]}\"");
        }
        index++;
        yield return new XElement("value", string.Join(",",lineList));
    }
}

Demo Code

【讨论】:

    【解决方案2】:

    LINQ:

    donnees.Select(d =>
    {
       string[] items = d.Select(i => "\" + i + "\")).ToArray();
       return $"<value>{string.Join(", ", items)}</value>");
    }
    

    【讨论】:

    • 虽然这个答案可能是正确的,但您应该通过解释此代码的作用以及它如何解决原始问题来提高答案的质量——这有助于阅读您的答案的其他用户了解什么正在进行中。
    【解决方案3】:

    只需按 index 进行迭代:

    var result = new List<(string, string, string)>();
    for(int i = 0; i < donnees[0].Count; i++)
    {
        result.Add((donnes[0][i], donnees[1][i], donnees[2][i]));
    }
    

    【讨论】:

    • 这不是假设每个列表只有三个元素吗?
    • @CaseyCrookston 当然。不过,我不确定这是好事还是坏事。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-21
    • 1970-01-01
    • 2021-06-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多