Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Search a String in List<Tuple<string,string>> in C#

Tags:

c#

list

tuples

I am having a

        List<Tuple<string,string>> tr = new List<Tuple<string,string>>();
        tr.Add(new Tuple<string, string>("Test","Add");
        tr.Add(new Tuple<string, string>("Welcome","Update");

        foreach (var lst in tr)
         {
             if(lst.Contains("Test"))
              MessageBox.Show("Value Avail");

          }

I failed while doing this ,....

like image 564
Aravind Avatar asked Jan 03 '13 06:01

Aravind


People also ask

How to access element in tuple C#?

A tuple elements can be accessed with Item<elementNumber> properties, e.g., Item1, Item2, Item3, and so on up to Item7 property. The Item1 property returns the first element, Item2 returns the second element, and so on. The last element (the 8th element) will be returned using the Rest property.

What is list tuple in C#?

A tuple is a data structure that contains a sequence of elements of different data types. Tuple<int, string, string> person = new Tuple <int, string, string>(1, "Test", "Test1"); A tuple can only include a maximum of eight elements. It gives a compiler error when you try to include more than eight elements.

What is ac tuple?

C# tuple is a data structure that provides an easy way to represent a single set of data. The System. Tuple class provides static methods to create tuple objects.


2 Answers

Probably this should work:

foreach (var lst in tr)
{        
    if (lst.Item1.Equals("Test"))        
        MessageBox.Show("Value Avail");
}

or this

if (lst.Item1.Equals("Test") || lst.Item2.Equals("Test"))

Read Tuple Class; you'll need to access values of the tuple through Item1 and/or Item2 properties.


And why use Tuple at all? Maybe this is easier:

Dictionary<string, string> dict = new Dictionary<string, string>
{
    {"Test", "Add"},
    {"Welcome", "Update"}
};

if (dict.ContainsKey("Test"))
{
    MessageBox.Show("Value Avail:\t"+dict["Test"]);
}
like image 64
horgh Avatar answered Sep 18 '22 20:09

horgh


If you'd like to use LINQ:

if(tr.Any(t => t.Item1 == "Test" || t.Item2 == "Test"))
    MessageBox.Show("Value Avail");

This will also have the benefit of only showing the message box once if the text is found multiple times (if that is what is desired).

like image 42
jam40jeff Avatar answered Sep 21 '22 20:09

jam40jeff