简体   繁体   中英

How can I print tuple nested in list in c#?

I have a function to fill a List which contains Tuple . It takes a dictionary as parameter and fills the list.

I need this to assign numerical values to text values.

For the sake of clearance;

I have an attribute section which includes let's say;

Attribute: Overcast

Text values for overcast: sunny, rainy, foggy etc.

Attribute: Temperature

Text values for it: hot, cold, mild

List has datas as attribute, value as text and value as number.

And I have data section. Which has values like "sunny, cold", "sunny, hot" etc.

My aim is to assign numbers and express data like "1,2", "1,3" and so on. To achieve that I wrote a function.

public List<Tuple<string, string, int>> SetNumAttrb(Dictionary<string, string[]> dic)
    {
        List<Tuple<string, string, int>> attNumNom = new List<Tuple<string, string, int>>();
        int ctrl = 1;
        foreach (KeyValuePair<string, string[]> kvp in dic)
        {
            for (int i = 0; i < kvp.Value.Length; i++)
            {
                attNumNom.Add(Tuple.Create<string, string, int>(kvp.Key, dic[kvp.Key][i], ctrl));
                ctrl++;
            }
        }
        return attNumNom;
    }

Now I need to print this to check if it is working correctly and I am going to need to access its content. How can I do that?

It's pretty straightforward. Just iterate over the list and print the contents of the tuple.

List<Tuple<string, string, int>> list = SetNumAttrb(dict);

foreach (var tuple in list)
{
    Console.WriteLine("{0} - {1} - {2}", tuple.Item1, tuple.Item2, tuple.Item3.ToString());
}

Maybe I misunderstand, but if you use:

Console.WriteLine(string.Join("\r\n", attNumNom));

you will print each List<> item, separated by CR LF (newlines).

Since Tuple<,,> overrides ToString() , that should be quite readable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM