根据条件比较两个列表 - C#

时间:2017-06-14 22:00:11

标签: c# list

我有两个单独的In [60]: np.random.seed([3,1415]) In [61]: a = np.random.choice([True, False], (400, 80)) In [57]: %timeit np.logical_and.accumulate(a, axis=0) 10000 loops, best of 3: 85.6 µs per loop In [59]: %timeit a.cumprod(0).astype(bool) 10000 loops, best of 3: 138 µs per loop 类型列表:

<double>

我希望第一次在List2&gt; List1 中的值 时得到索引号,即在上面的例子中,索引= 4为400> 200。

4 个答案:

答案 0 :(得分:2)

int position;
for(int i = 0; i < List2.Count; ++i)
{
    if(List2[i] > List1[i]) // or Math.Abs(List2[i]-List1[i]) > epsilon
    {
        position = i; 
        break;
    }
}

答案 1 :(得分:2)

您可以使用Zip(组合列表)和TakeWhile(迭代直到条件满足/不满足)来实现此目的。如果listA和listB的大小不同,此代码也可以正常工作。

using System;
using System.Collections.Generic;
using System.Linq;

namespace Test
{
    public class Program
    {
        static void Main()
        {
            var listA = new List<int>() { 1, 2, 3, 4, 5 };
            var listB = new List<int>() { 1, 2, 3, 4, 6 };

            var combined = listA.Zip(listB, (first, second) => new { first, second })
                .TakeWhile(z => z.first >= z.second); ;
            var countWhereListIsGreater = combined.Count();

            var index = (countWhereListIsGreater >= listA.Count || 
                countWhereListIsGreater >= listB.Count)
                ? -1
                : countWhereListIsGreater;

            Console.WriteLine(index);
            Console.ReadLine();
        }
    }
}

如果您确定这两个列表的大小相同,那么这也可以:

        static void Main()
        {
            var listA = new List<int>() { 1, 2, 3, 4, 5 };
            var listB = new List<int>() { 1, 2, 3, 4, 6 };

            var result = listA.Select((currentValue, index)
                => new { currentValue, index })
                .Where(z => listB[z.index] > z.currentValue)
                .Select(z => (int?)z.index).FirstOrDefault() ?? -1;

            Console.WriteLine(result);
            Console.ReadLine();
        }

答案 2 :(得分:1)

 static int Position(List<double> list1, List<double> list2) 
 for(int i =0; i < list1.Count; i++) 
 {
 if(list2[i] > list1[i]) return i;
 } 
 return -1;

如果返回的位置为-1,则意味着在第二个列表中没有任何数字&gt;而不是在第一个列表中。你这样称呼它

 int position = Position(List1, List2);

答案 3 :(得分:1)

list1.IndexOf(list1.Where((currentValue, index) => list2[index] > currentValue).FirstOrDefault());

旁注: list2尺寸&gt; = list1尺寸。或者在

之前检查