【问题标题】:Find indexes of foreach Tuple List Item equals to given Item查找 foreach 元组列表项的索引等于给定项
【发布时间】:2020-04-20 12:15:32
【问题描述】:

我想找到 Tuple List 值的 foreach Item1 的索引等于给定字符串 "png"

但我找不到正确的 foreach 条件 来搜索它。任何帮助都会很好..

List<Tuple<string, string>> fileConverterList = new List<Tuple<string, string>>()
        {
            Tuple.Create("png","jpg"),
            Tuple.Create("jpg","bmp"),
            Tuple.Create("png","bmp")
        };

string = "png";

foreach (int i in /* fileConverterList condition */)
        {
            // Provided conditions must be: i = 0 and i = 2. That means;
            // fileConverterList[0].Item1 equals to "png" and
            // fileConverterList[2].Item1 equals to "png"
        }

【问题讨论】:

    标签: c# list foreach tuples


    【解决方案1】:

    您可以使用 LINQ 查找所有索引,如下所示:

    var indexes = myTuples.Select((t, i) => new { t, i })
                          .Where(x => x.t.Item1 == "png")
                          .Select(y => y.i);
    

    这是一个演示控制台应用程序:

        static void Main(string[] args)
        {
            var myTuples = new List<Tuple<string, string>>
            {
                new Tuple<string, string>("png", "jpg"),
                new Tuple<string, string>("jpg", "bmp"),
                new Tuple<string, string>("png", "bmp")
            };
    
            var indexes = myTuples.Select((t, i) => new { t, i })
                                  .Where(x => x.t.Item1 == "png")
                                  .Select(y => y.i);
    
            Console.WriteLine("Indexes:");
            foreach (var index in indexes)
            {
                Console.WriteLine("Index: " + index);
            }
    
            Console.ReadLine();
        }
    

    结果:

    【讨论】:

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