C# - 如何使用两个foreach循环的结果创建KeyValuePair?

时间:2017-04-11 13:15:23

标签: c# arrays linq loops key-value

以下是我目前拥有的代码(它不起作用,因为最后一个块看到数组是未定义的,它是为了显示我想要做的事情)

IEnumerable<string> sponsorshipQuery1 =
  from runner1 in venueQuery6.Descendants("Runner")
  where (int)runner1.Element("Sponsorship") > 0
  orderby (int)runner1.Element("Sponsorship") descending
  select runner1.Element("Firstname").Value;

IEnumerable<string> sponsorshipQuery2 =
  from runner1 in venueQuery6.Descendants("Runner")
  where (int)runner1.Element("Sponsorship") > 0
  orderby (int)runner1.Element("Sponsorship") descending
  select runner1.Element("Sponsorship").Value;

string[] nameArray;
string[] moneyArray;

foreach (string name in sponsorshipQuery1)
{
  nameArray = sponsorshipQuery1
    .OfType<object>()
    .Select(o => o.ToString()).ToArray();
}

foreach (string money in sponsorshipQuery2)
{
  moneyArray = sponsorshipQuery2
    .OfType<object>()
    .Select(o => o.ToString())
    .ToArray();
}

Console.WriteLine("All sponsorship money raised in descending order:");
for (int i = 0; i < nameArray.Length; i++)
{
  Console.WriteLine(nameArray[i] + " has raised £" + moneyArray[i]);
}

理想情况下,我希望能够在底部执行for循环。我猜想要替换两个foreach循环并使它们成为KeyValuePairs但我不知道该怎么做。

我也是使用Linq查询的新手,所以我混合使用查询语法和=&gt;语法是因为我教过查询语法,但我也在尝试在互联网上找到的代码。

2 个答案:

答案 0 :(得分:6)

从您的示例代码中可以看出,您可以在一个查询中获取这两个值,并将它们保存为匿名类型:

var results = from runner1 in venueQuery6.Descendants("Runner")
                  where (int)runner1.Element("Sponsorship") > 0
                  orderby (int)runner1.Element("Sponsorship") descending
                  select new { 
                     Name = runner1.Element("Firstname").Value,
                     Amount = runner1.Element("Sponsorship").Value
                  };

然后你可以循环这些结果:

foreach (var result in results)
{
    Console.WriteLine(result.Name + " has raised £" + result.Amount);
}

答案 1 :(得分:2)

串联迭代两个序列的最高级方法是使用Zip。要获得KeyValuePair,请使用

sponsorshipQuery1.Zip(sponsorshipQuery2, (k, v) => new KeyValuePair<string, string>(k, v))

虽然我可能根本不会使用KeyValuePair,但是我的任务或匿名类型更具体,除非我真正关心它作为键和值对。

迭代你已经涵盖过的两个阵列。要对两个foreach进行双重IEnumerable<T>无法(必然)编入索引,需要将至少一个循环分解为其组件MoveNext()和{{ 1}}

Current

在您的特定示例中,因为您有一个共同的来源:

using (var en1 = sponsorshipQuery1.GetEnumerator())
{
  foreach(var item2 in sponsorshipQuery2)
  {
    if (!en1.MoveNext())
    {
      break;
    }
    var item1 = en.Current;
    // Do something with the two items here. E.g.
  }
}

我只是from runner1 in venueQuery6.Descendants("Runner") where (int)runner1.Element("Sponsorship") > 0 orderby (int)runner1.Element("Sponsorship") descending 开始。