如何找到属于列表的任何范围的数字
本文关键字:任何 数字 范围 列表 何找 属于 | 更新日期: 2023-09-27 17:54:49
我有一个列表和一个数组,我想找到数组中属于列表的任何范围的每个元素。下面是一些代码:
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}
我希望我有你想要的。
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}
您需要使用以下逻辑(在伪代码中,带有示例数字):
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
这应该为你指明解决问题的正确方向。试一试,如果有任何问题请告诉我们。
您可以使用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);
}
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){ }
}
}