如何查找列表中任何范围的数字?

时间:2013-01-20 12:38:03

标签: c#

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

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,我看到范围(列表中的任何数字之间)通过列表==&gt;回答1.5和2.6

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

  

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

4 个答案:

答案 0 :(得分: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 {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} 
} to {{{2}}} ", val, lower, upper);
}

打印:

{{1}}

答案 1 :(得分: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

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

答案 2 :(得分: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){ }
    }
}

答案 3 :(得分: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);
   }