3

I am creating a list of named tuples. I propulate this list using the add method but after this process, I realize that the tuples' members have lost their custom names being accessible only by "Item1", "Item2"...

I am using .NET framework version 4.6.2, C# 7.3

private static List<(string name, string url)> GetItemsNamesAndUrls(IEnumerable<MyItems> itemsList)
    {
        List<(string name, string url)> result = new List<(string name, string url)>();
        foreach (var item in itemsList)
        {
            result.Add((name: item.Name, url: GetItemUrlFromName(item.Name)));
        }
        return result;
    }

MyItem class is very simple:

class MyItems
{
    public string Name { get; set; }
}

After the result list being populated, I expect to be able to access the named tuples members by the custom names, not using Item1 and Item2.

  • Could you post code from "MyItems" class ? – Mr.Deer Aug 07 '19 at 13:29
  • https://blogs.msdn.microsoft.com/mazhou/2017/05/26/c-7-series-part-1-value-tuples/ – Train Aug 07 '19 at 13:33
  • Can you add a simple code example to reproduce the problem? Because this worked: https://i.stack.imgur.com/mkIG2.png – stuartd Aug 07 '19 at 13:37
  • Yes, it seems to be it is working in a console application. So, maybe the problem is not related with that code itself, but with what I do with the result of that code. The returned list is passed as part of a view model to an MVC view. There, in the view, I get the exception with the following information: Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: ''System.ValueTuple' does not contain a definition for 'url'' – user2634979 Aug 07 '19 at 13:53

1 Answers1

0

Tuple value names equate to method variables. They are only valid where declared.

Using your GetItemsNamesAndUrls method, this is valid code:

var l = GetItemsNamesAndUrls(itemsList);
var t1 = l[0];
var n = t1.name;
var u = t1.url;
(string x, string y) t2 = t1;
var x = t2.x;
var y = t2.y;
var (a, b) = t1;
var c = t1 == t2; // true
Paulo Morgado
  • 14,111
  • 3
  • 31
  • 59