简体   繁体   English

在列表中找到最高的小数字<int>

[英]Find the highest small number in List <int>

I'm having two lists and both are sorted. 我有两个列表,并且都已排序。

List<int> listA = new List<int>();
// It has { 9,15,21,25,27,33,.......}


List<int> listB = new List<int>();
// it has { 2,3,5,7,11,13,17........}

I'm trying to iterate List A values and get the highest small number in List B means. 我正在尝试迭代列表A的值,并获得列表B平均值中的最高小数字。

foreach (var k in listA)
{
 // if 9 in list A  get 7 in list B 
 // if 15 in list A  get 13 in list B  
 // and without iterating entire list B 
}

How? 怎么样?

Try this code: 试试这个代码:

List<int> listA = new List<int> { 9, 15, 21, 25, 27, 33 };
List<int> listB = new List<int> { 2, 3, 5, 7, 11, 13, 17 };

int j = 0;
foreach (int item in listA)
{
    while (j < listB.Count && listB[j] < item)
        j++;
    if (j > 0)
        Console.WriteLine(listB[j - 1]);
}

It iterates through the listA and increases the current index in the listB when necessary. 它循环通过listA ,并增加了在当前指数listB必要时。

Edit:Note the "without iteration requirement" was added later 编辑:请注意“无迭代要求”后来添加

foreach (var k in listA)
{
   listB.Where(x=>x<k).Max();
}

this will give an error if there is no value smaller than k(ie listB.Where(x=>x 如果没有小于k的值,则将给出错误(即listB.Where(x => x

foreach (var k in listA)
{
 listB.Where(x=>x<k).OrderByDescending(x=>x).FirstOrDefault();
}

This does the job: 这样就可以了:

var listA = new List<int> { 9, 15, 21, 25, 27, 33, };
var listB = new List<int> { 2, 3, 5, 7, 11, 13, 17, };

var be = listB.GetEnumerator();

var last = be.Current;
foreach (var a in listA)
{
    while (be.MoveNext())
    {
        var current = be.Current;
        if (current >= a)
        {
            Console.WriteLine(String.Format("{0} {1}", a, last));
            break;
        }
        last = current;
    }
}

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

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