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

后端 未结 19 732
后悔当初
后悔当初 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:05

    Changing shapes of objects when you need to send them across wire or pass to different layer of application and multiple objects get merged into one:

    Example:

    var customerDetails = new Tuple>(mainCustomer, new List
    {mainCustomerAddress}).ToCustomerDetails();

    ExtensionMethod:

    public static CustomerDetails ToCustomerDetails(this Tuple> customerAndAddress)
        {
            var mainAddress = customerAndAddress.Item2 != null ? customerAndAddress.Item2.SingleOrDefault(o => o.Type == "Main") : null;
            var customerDetails = new CustomerDetails
            {
                FirstName = customerAndAddress.Item1.Name,
                LastName = customerAndAddress.Item1.Surname,
                Title = customerAndAddress.Item1.Title,
                Dob = customerAndAddress.Item1.Dob,
                EmailAddress = customerAndAddress.Item1.Email,
                Gender = customerAndAddress.Item1.Gender,
                PrimaryPhoneNo = string.Format("{0}", customerAndAddress.Item1.Phone)
            };
    
            if (mainAddress != null)
            {
                customerDetails.AddressLine1 =
                    !string.IsNullOrWhiteSpace(mainAddress.HouseName)
                        ? mainAddress.HouseName
                        : mainAddress.HouseNumber;
                customerDetails.AddressLine2 =
                    !string.IsNullOrWhiteSpace(mainAddress.Street)
                        ? mainAddress.Street
                        : null;
                customerDetails.AddressLine3 =
                    !string.IsNullOrWhiteSpace(mainAddress.Town) ? mainAddress.Town : null;
                customerDetails.AddressLine4 =
                    !string.IsNullOrWhiteSpace(mainAddress.County)
                        ? mainAddress.County
                        : null;
                customerDetails.PostCode = mainAddress.PostCode;
            }
    ...
            return customerDetails;
        }
    

提交回复
热议问题