如何将字典键和值作为字符串C#分配给变量

时间:2018-07-04 16:19:00

标签: c# asp.net-mvc

我正在尝试发送电子邮件,并将字典键和值作为字符串分配给变量。

public ActionResult SendContactUs(ContactUsModel model)
    {
        SendEmail sendemail = new SendEmail();

        string toEmail = ConfigurationManager.AppSettings["ContactUsEmail"];

        var keys = new Dictionary<string, string>() {
            { "Firstname", model.Firstname },
            { "Lastname", model.Lastname },
            { "Email", model.Email },
            { "Orgnization", model.Orgnization },
            { "Message", model.Message }
        };
   //here i want to pass keys  to body as string 
        string body = keys ;




        sendemail.Send(new EmailModel()
        {
            Body = body,
            To = new List<string>() { toEmail },

       });

        return Json(new { val = true }, JsonRequestBehavior.AllowGet);
    }

例如,我想将字符串体显示为

FirstName: scscd
LastName : dcdcdcd
Email : dcdcd@dsds.rfrfr
Message : vxvxcvxcvxcvxcv

1 个答案:

答案 0 :(得分:2)

您可以使用Linq构造字符串:

string body = string.Join(Environment.NewLine, keys.Select(x=>$"{x.Key}: {x.Value}"));