繁体   English   中英

从 1 项中查找元组列表的索引

[英]Find Index of List of Tuples from 1 item

请考虑 C# 中的元组列表。 这与原始元组(而不是值元组)有关。 如果我知道元组列表中的项目之一,如何获取列表的索引?

        List<Tuple<double, int>> ListOfTuples2 = new 
        List<Tuple<double, int>>();

        double doubleTuple = 5000;
        int intTuple = 7;

        ListOfTuples2.Add(Tuple.Create(doubleTuple, intTuple));
        ListOfTuples2.Add(Tuple.Create(5000.00, 2));
        ListOfTuples2.Add(Tuple.Create(5000.25, 3));
        ListOfTuples2.Add(Tuple.Create(5000.50, 4));
        ListOfTuples2.Add(Tuple.Create(5000.25, 5));


        /* How can I get the Index of the List if 
        doubleTuple = 5000.25 ?  */  

您可以使用接受谓词作为参数的列表的FindIndex方法

int index = ListOfTuples2.FindIndex(t => t.Item1 == 5000.25);
if (index > = 0) {
    // found!
}

如果没有找到这样的项目, FindIndex返回-1


但您可能会考虑使用字典代替。 如果集合很大,它会比列表更快地找到条目。 Big O 表示法的检索次数: List<T>O(n)Dictionary<K,V>O(1) 但是,字典中的项目没有排序,也没有索引。 此外,键必须是唯一的。 如果您需要订购的物品,请遵守清单。

var dict = new Dictionary<double, int>{
    [doubleTuple] = intTuple,
    [5000.00] = 2,
    [5000.25] = 3,
    [5000.50] = 4,
    [5000.25] = 5
}

if (dict.TryGetValue(5000.25, out int result)) {
    // result is 3; and contains the value, not the index.
}

您还可以添加条目

dict.Add(5000.75, 8);

如果您确定字典包含一个条目,您可以简单地检索它

int result = dict[5000.25];

此外,如果您要处理价格,请考虑使用decimal类型。 If 是专门为金融和货币计算而创建的。 double类型将值存储为二进制数。 0.1 (十进制)是0.000110011001100110011001100110011... (二进制),即double引入了舍入错误,仅通过将十进制常量转换为其二进制表示,而decimal按原样存储常量的每个十进制。 double对于科学计算来说是可以的(而且速度更快)。 温度是 29.7 度还是 29.69999999999 度都没有区别,因为无论如何您都可以以非常有限的精度(可能是 1%)进行测量。


C# 7.0 添加了ValueTuple类型以及元组类型和元组值的简单语法。 考虑用这个新特性替换Tuple类。

var listOfValueTuples = new List<(double, int)> {
    (doubleTuple, intTuple),
    (5000.00, 2),
    (5000.25, 3),
    (5000.50, 4),
    (5000.25, 5)
};

如果您想获取所有索引,您可以编写以下代码:

var indexes = ListOfTuples2.Select((tuple, index) => new {tuple, index}).Where(o => Math.Abs(o.tuple.Item1 - 5000.25) < 1e-5).Select(o => o.index - 1);
foreach (var index in indexes)
{
    Console.WriteLine(index);
}

请注意,比较两个浮点数可能会返回不可预测的结果,因此我使用Math.Abs方法进行比较

暂无
暂无

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

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