Sillyon
Sillyon

Reputation: 45

Find indexes of foreach Tuple List Item equals to given Item

I want to find indexes of foreach Item1 of Tuple List values equals to given string "png".

But I couldn't find what is the right foreach condition was to search for it. Any help would be nice..

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"
        }

Upvotes: 0

Views: 81

Answers (1)

sr28
sr28

Reputation: 5106

You can use LINQ to find all the indexes like this:

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

Here it is in a demo console app:

    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();
    }

Results:

enter image description here

Upvotes: 1

Related Questions