简体   繁体   English

使用双精度列表中的 foreach 循环创建字符串列表。 每两个值必须压缩成一个字符串,然后添加到列表中

[英]create a list of strings using a foreach loop from list of doubles. every two values must be compressed into a single string then added to list

I hope someone has a good was of solving this problem.我希望有人能很好地解决这个问题。

So I have a list of doubles these being coordinates, example -123123, 12313. shown in image below.所以我有一个双打列表,这些是坐标,例如 -123123, 12313。如下图所示。

List of doubles双打名单

these are being used in this foreach loop:这些在这个 foreach 循环中被使用:

foreach (var coord in element.geometry.coordinates)
{


}

I'm trying to make a list of said coordinates - but instead of them being a list of single coordinates I need them to be compressed into two.我正在尝试列出上述坐标 - 但不是它们是单个坐标的列表,我需要将它们压缩为两个。

So rather than a list of所以而不是一个列表

  • -1213123 -1213123
  • 1345 1345
  • -345 -345
  • 1234535 1234535

I need a list of strings like so.我需要一个像这样的字符串列表。

  • -1213123, 1345 -1213123, 1345
  • -345, 1234535 -345, 1234535

using var 'coord' this being a single coordinate when coming out of the foreach loop.使用 var 'coord' 这是从 foreach 循环出来时的单个坐标。 how can I create a list pairing every two values that come out of the loop.如何创建一个列表,将循环中的每两个值配对。

Thanks for any help given :)感谢您提供的任何帮助:)

if the foreach loop is compulsory, then如果 foreach 循环是强制性的,那么

string[] lst = new string[element.geometry.coordinates.Count() / 2];

int i=0;
foreach (var coord in element.geometry.coordinates)
{
    if (i % 2 == 1) 
        lst[i-1] = $"{lst[i-1]}, coord";
    else
        lst[i] = coord

    ++i;

}

I know it looks a little bit weird, but you can you Linq.Zip method.我知道它看起来有点奇怪,但是您可以使用 Linq.Zip 方法。

        var coordinates = element.geometry.coordinates;
        var result = coordinates
            .Where((_, index) => index % 2 == 0) // Get even numbers
            .Zip(
                coordinates.Where((_, index) => index % 2 == 1), // Get odd numbers
                (first, second) => $"{first}, {second}") // Zip them together
            .ToList(); // If you need the result as List<string>

You cannot take a step other than 1 in a foreach loop.您不能在foreach循环中执行除 1 以外的步骤。 Therefore I propose to use a for loop instead.因此我建议改用for循环。 It can be set to step 2.可以设置为步骤2。

var doubles = new List<double> { -1213123, 1345, -345, 1234535 };
var strings = new List<string>();

for (int i = 0; i < doubles.Count; i += 2)
{
    strings.Add(doubles[i] + ", " + doubles[i + 1]);
}

Do not need extra conditional if statements.不需要额外的条件if语句。 This solution turns out to be as simple and effective as possible.事实证明,该解决方案尽可能简单有效。

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

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