-1

我有一个列表和一个数组,我想为属于该列表的任何范围找到数组中的每个元素。这是一些代码:

int[] number = {1, 2, 3, 5};
public List<double> m = new List<double>();
m.add(1);
m.add(1.5);
m.add(2.6);
m.add(4);
m.add(50);

例如:获取数组中的元素,例如 2,我看到范围(在列表中的任何数字之间)通过列表 ==> 1.5 和 2.6 回答

我想要一个返回这个输出的方法:

find 1 range is {1} to {1.5} and 2 range is {1.5} to {2.6}

4

4 回答 4

0

我希望我已经得到了你想要的。

void Main()
{
    var numbers =new [] {1, 2, 3, 5};

    //ordering to make sure that ranges is ascending order
    var orderedRanges = new []{1, 1.5, 2.6, 4, 50}.OrderBy(v => v);

    var valuesInRanges = numbers.Select(number => 
                          FormatValueInRange(
                            number,
                            orderedRanges.Last(range => range <= number ),
                            orderedRanges.First(range => range > number )));

    var result = "Find " + string.Join("and ", valuesInRanges);

    Console.WriteLine (result);
}

private string FormatValueInRange(double val, double lower, double upper)
{
    return string.Format(@"{0} is {{{1}}} to {{{2}}} ", val, lower, upper);
}

印刷:

Find 1 is {1} to {1.5} and 2 is {1.5} to {2.6} and 3 is {2.6} to {4} and 5 is {4} to {50} 
于 2013-01-20T13:01:31.300 回答
0

您需要使用以下逻辑(在伪代码中,带有示例编号):

rangeStart = 1
rangeEnd = 7

numberOne = 3.7

if numberOne >= rangestart and numberOne <= rangeEnd
    // number is in range

numberTwo = 12

if numberTwo >= rangestart and numberOne <= rangeEnd
    // number is NOT in range

这应该为您指明解决问题的正确方向。试一试,如果您有任何问题,请告诉我们。

于 2013-01-20T13:04:18.063 回答
0
int[] numbers = new int[] { 1, 2, 3, 5 };
List<double> m = new List<double>();
m.Add(1);
m.Add(1.5);
m.Add(2.6);
m.Add(4);
m.Add(50);

foreach (int n in numbers)
{
    for (int i = 0; i < m.Count; i++)
    {
        try
        {
            if (m[i] <= n && m[i + 1] >= n)
                MessageBox.Show(
                    string.Format("{0} is between {1} and {2}",
                    n, m[i], m[i + 1]));
        }
        catch (Exception){ }
    }
}
于 2013-01-20T13:05:36.267 回答
0

您可以使用 LINQ。

 List<double> m = new List<double>();
   m.Add(1);
   m.Add(1.5);
   m.Add(2.6);
   m.Add(4);
   m.Add(50);

   m.Sort();

   int[] numbers = { 1, 2, 3, 5 };
   foreach (var item in numbers)
   {
        double min = m.Where(x => x <= item).Last();
        double max = m.Where(x => x > item).First();

        Console.WriteLine("find {0} range is {1} to {2}", item, min, max);
   }
于 2013-01-20T13:07:51.117 回答