我有两个列表
List<double> numbers1 = [1,3,5,6,4.5,2.1,.......];
List<double> numbers2 = [.5,3.2,5.4,6,4.5,2.1,.......];
我想比较list1中的[1]与[。[5]
if([1] close to[.5])
为例
表示如果第一个列表中的第一个项值接近第二个列表中的第一个项值等等,第二个是第二个,第三个是第三个
我怎么做这个c#?
使用Math.Abs
检查两个相关项之间的差异:
bool allElementsClose = true;
for(int i = 0; i < lis1.Count && allElementsClose; i++)
{
if(Math.Abs(list1[i] - list2[i]) > threshold)
{
Console.WiteLine("items not close");
allElementsClose = false;
break;
}
}
但是,在迭代之前,您应该对项目的数量进行一些检查。
使用LINQ:
的替代方法var allElementsClose = list1
.Select((x, i) => Math.Abs(x - list2[i]))
.All(x => x < threashhold);
这种方法使用select的重载,它使用Func<T, int>
来获取集合中的元素及其索引。然后可以使用该索引在第二个列表中获取相应的项,并计算与它的差值。
最简单的解决方案是使用Zip,它用于比较两个集合的每个映射元素,并且还将处理元素数量的差异,因为它在内部检查Enumerator.MoveNext()
var result = numbers1.Zip(numbers2,(n1,n2) => n1 - n2 < 0.5 ? "Close" : "Not Close");
result
将IEnumerable<string>
包含值"Close" and "Not Close"
注意:
- 你的问题有很多细节缺失,因为我不确定什么是"接近",什么是"不接近",我假设两个数字之间的差异小于0.5是接近的,根据要求修改
实际上这取决于"close"对你来说意味着什么。如果这两个数之间的差小于1,我就假定它们很接近。
所以代码会非常简单
我将创建三个列表。list1, list2, listResult(它将只包含布尔值,表示list1中的项是否接近list2中的项。
var list1 = new List<float>();
var list2 = new List<float>();
var listResult = new List<bool>();
上面的3行应该放在方法或事件之外,如button1_click。
//to add values to the list you can use list1.addNew(5) and it will add the "5" to the list
void CompareLists(){
//first of all we check if list1 and list2 have the same number of items
if(list1.Count == list2.Count){
for (int i=0; i<list1.Count; i++){
if (list1[i] - list2[i] < 1)
listResult.addNew(true);
else
listResult.addNew(false);
}
}
}
现在你有了一个像(真正的),(真正的),(假)
希望它对你有用。
在。net 4.0中,您还可以使用Zip()
:
var numbers1 = new List<double>() { 1, 3, 5, 6, 4.5, 2.1 };
var numbers2 = new List<double>() { 0.5, 3.2, 5.4, 6, 4.5, 2.1 };
var allElementsClose = numbers1
.Zip(numbers2, (i1, i2) => Math.Abs(i1 - i2))
.All(x => x < threshold);