【问题标题】:Find Index of List of Tuples from 1 item从 1 项中查找元组列表的索引
【发布时间】:2019-05-27 12:00:40
【问题描述】:

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

【问题讨论】:

  • 你尝试了什么?使用 fx linq 应该很容易
  • 我的意思是列表的索引。在这种情况下,如果 doubleTuple = 5000.25,则 Return 应为 2(因为它是第三个,第一个是 0)

标签: c# list indexing tuples


【解决方案1】:

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

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

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


但您可以考虑改用字典。如果集合很大,它会比列表更快地找到条目。 Big O notation中的检索次数:List&lt;T&gt;O(n)Dictionary&lt;K,V&gt;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)
};

【讨论】:

  • 非常感谢!!有用!我是一个新手,一直被这个问题困扰!
【解决方案2】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-11-05
    • 2021-05-30
    • 2020-09-15
    • 2010-09-15
    • 2020-07-31
    • 1970-01-01
    • 2014-10-13
    相关资源
    最近更新 更多