繁体   English   中英

具有相同条件的List字符串的Loop List提取C#

[英]Loop List of List string with a condition the same order on the extraction C#

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

  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
}
}

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

您实际上是在尝试按列读取列表列表,然后组合结果。 您可以使用嵌套循环来做到这一点。

以下方法应该可以帮助您创建所需的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));
    }
}

演示代码

只需按索引迭代:

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

林克:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM