将3个列表保存为以逗号分隔的文本

时间:2013-12-12 18:36:50

标签: c# list foreach

我有三份成分,数量和单位清单。我需要将所有三个保存到以逗号分隔的文本文件中。例如[ingredient],[amount],[units]。我目前正在使用嵌套的foreach循环,但这样可以保存它们的每个组合。我该如何解决这个问题?

foreach (string q in ingredients)
{
    foreach (int w in newAmounts)
    {
        foreach (string r in units)
        {
            writer.Write(q + ",");
            writer.Write(w + ",");
            writer.Write(r + "\n");
        }
    }
}

由于

3 个答案:

答案 0 :(得分:0)

如果您的所有列表都具有相同的计数,那么您可以使用一个for循环而不是三个foreach:

for(int i=0; i<ingredients.Count;i++)
{
   writer.Write(ingredients[i] + ",");
   writer.Write(newAmounts[i] + ",");
   writer.Write(units[i] + "\n");
 }

答案 1 :(得分:0)

  for (int i = 0; i < ingredients.Length; i++)
  {
    writer.Write(string.Format("{0}, {1}, {2}\n", ingredients[i], newAmounts[i], units[i]);
  }

答案 2 :(得分:0)

您需要的是Enumerable.Zip。它需要两个IEnumerable s并将它们转换为新类型的IEnumerable。如果三个集合与索引匹配,则代码如下所示:

var tuples = ingredients
    .Zip(newAmounts,
        (i, a) => new Tuple<string, string>(i, a))
    .Zip(units,
        (t, a) => new Tuple<string, string, string>(t.Item1, t.Item2));

foreach (var t in tuples)
{
    writer.Write(t.Item1 + ",");
    writer.Write(t.Item2 + ",");
    writer.Write(t.Item3 + "\n");
}

代码可能看起来有点难看,但你可以通过添加一些ZipToTuple帮助程序函数来改善代码。

public static IEnumerable<Tuple<T1, T2>> ZipToTuple<T1, T2>(
    this IEnumerable<T1> e1,
    IEnumerable<T2> e2)
{
    return e1.Zip(e2,
        (t1, t2) => new Tuple<T1, T2>(t1, t2));
}

public static IEnumerable<Tuple<T1, T2, T3>> ZipToTuple<T1, T2, T3>(
    this IEnumerable<T1> e1,
    IEnumerable<T2> e2,
    IEnumerable<T3> e3)
{
    return e1
        .ZipToTuple(e2)
        .Zip(e3,
            (t, t3) => new Tuple<T1, T2, T3>(t.Item1, t.Item2, t3));
}

然后代码变为:

foreach (var t in ingredients.ZipToTuple(newAmounts, units))
{
    writer.Write(t.Item1 + ",");
    writer.Write(t.Item2 + ",");
    writer.Write(t.Item3 + "\n");
}