Practical example where Tuple can be used in .Net 4.0?

后端 未结 19 690
后悔当初
后悔当初 2020-12-04 07:44

I have seen the Tuple introduced in .Net 4 but I am not able to imagine where it can be used. We can always make a Custom class or Struct.

19条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-04 08:20

    Just found the solution of one of my issues in Tuple. It is like declaring a class in scope of a method, but with lazy declaration of its fields names. You operate with collections of tuples, its single instances and then create a collection of anonymous type with the required field names, basing on your tuple. This avoids you from creating the new class for this purpose.

    The task is to write a JSON response from LINQ without any additional classes:

     //I select some roles from my ORM my with subrequest and save results to Tuple list
     var rolesWithUsers = (from role in roles
                           select new Tuple(
                             role.RoleName, 
                             role.RoleId, 
                             usersInRoles.Where(ur => ur.RoleId == role.RoleId).Count()
                          ));
    
     //Then I add some new element required element to this collection
     var tempResult = rolesWithUsers.ToList();
     tempResult.Add(new Tuple(
                            "Empty", 
                             -1,
                             emptyRoleUsers.Count()
                          ));
    
     //And create a new anonimous class collection, based on my Tuple list
     tempResult.Select(item => new
                {
                    GroupName = item.Item1,
                    GroupId = item.Item2,
                    Count = item.Item3
                });
    
    
     //And return it in JSON
     return new JavaScriptSerializer().Serialize(rolesWithUsers);
    

    Of cause we could do this with declaring a new Class for my groups, but the idea to create such an anonimous collections without declaring of new classes.

提交回复
热议问题