我<double>
類型的兩個單獨列表如下:比較基於條件的兩個列表 - C#
Index List1 List2
0 1000 -500
1 900 -200
2 600 100
3 400 250
4 200 400
5 100 500
6 50 1500
我想索引號的時候在列表2>列表1 首次值,即在上面的例子中,索引= 4爲400> 200。
我<double>
類型的兩個單獨列表如下:比較基於條件的兩個列表 - C#
Index List1 List2
0 1000 -500
1 900 -200
2 600 100
3 400 250
4 200 400
5 100 500
6 50 1500
我想索引號的時候在列表2>列表1 首次值,即在上面的例子中,索引= 4爲400> 200。
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;
}
}
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表示在第二列表中不存在任何數目>比在第一列表中。你把它像
int position = Position(List1, List2);
list1.IndexOf(list1.Where((currentValue, index) => list2[index] > currentValue).FirstOrDefault());
旁註:列表2尺寸> = list1的大小。或者在之前檢查它
要實現此目的,您可以使用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();
}
假設兩個列表具有相同的個性化......否則'INT MAXCOUNT = Math.Min( List1.Count,List2.Count);'和'for(int i = 0; i
謝謝..如果FOR循環不需要,是否有使用Linq語句的方法。 – user7157732
如果你想避免for循環,請查看我的替代答案。 for循環雖然完美無缺。 – mjwills