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

Rob*_*gic 0 c# indexing tuples list

请考虑C#中的元组列表.这与原始元组(不是Value Tuple)有关.如果我知道元组列表中的一个项目,我怎样才能获得List的索引?

        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 ?  */  
Run Code Online (Sandbox Code Playgroud)

Oli*_*bes 6

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

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

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.
}
Run Code Online (Sandbox Code Playgroud)

您还可以添加条目

dict.Add(5000.75, 8);
Run Code Online (Sandbox Code Playgroud)

如果您确定该词典包含一个条目,您可以使用它来检索它

int result = dict[5000.25];
Run Code Online (Sandbox Code Playgroud)

此外,如果您正在处理价格,请考虑使用该decimal类型.如果是专门为财务和货币计算而创建的.该double类型将值存储为二进制数.0.1(十进制)是0.000110011001100110011001100110011...(二进制),即double引入舍入误差,仅通过将十进制常量转换为其二进制表示,而decimal将常量的每个小数存储为原样.double科学计算是好的(并且更快).温度是29.7还是29.69999999999度没有区别,因为无论如何你都可以用非常有限的精度测量它(可能是1%).