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

时间:2018-12-30 16:11:32

标签: c# list indexing tuples

请考虑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 ?  */  

2 个答案:

答案 0 :(得分:6)

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

int index = ListOfTuples2.FindIndex(t => t.Item1 == 5000.25);
if (index > = 0) {
    // found!
}
如果没有找到

FindIndex,则返回-1


但是您可以考虑使用字典。如果集合很大,则查找条目的速度比列表快得多。 Big O notation中的检索时间: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类型。如果是专门为财务和货币计算而创建的。 double类型将值存储为二进制数。 0.1(十进制)是0.000110011001100110011001100110011...(二进制),即,double仅通过将十进制常数转换为其二进制表示形式就引入了舍入误差,而decimal存储每个十进制常量的原样。 double可以(而且更快)进行科学计算。温度是29.7还是29.69999999999度都没有区别,因为无论如何您都可以以非常有限的精度(也许是1%)进行测量。

答案 1 :(得分:0)

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

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方法进行比较

相关问题