Name Tuples/Anonymous Types in F#?

后端 未结 6 1628
执笔经年
执笔经年 2021-02-03 19:46

in C# you can do stuff like :

var a = new {name = \"cow\", sound = \"moooo\", omg = \"wtfbbq\"};

and in

6条回答
  •  醉梦人生
    2021-02-03 20:30

    The OP does not describe the best use of anonymous type. They are best used when using LINQ to map to an arbitrary class. For example:

    var results = context.Students
                  .Where(x => x.CourseID = 12)
                  .Select(x => new { 
                     StudentID = x.ID, 
                     Name = x.Forename + " " + x.Surname
                  });
    

    I know this can be done by defining a new record type, but then you have two places to maintain code, (1) the record type definition (2) where you've used it.

    It could instead be done with a tuple, but to access individual fields you have to use the deconstruction syntax (studentId, name) all the time. This becomes unwieldy if you have 5 items in the tuple. I would rather type in x and hit dot and have intellisense tell me what fields are available.

提交回复
热议问题