-1

I am using Mailkit to send an email.

So in the body of the email, I am passing data like this:

message.Body = new TextPart("plain")
{
    foreach (var item in model.Transaction)
    {
        Console.WriteLine(item.Account +"-"+item.Amount+"-"+item.Date);
    }

    Text = @"";
};

but I wanted to put item.Account, item.Amount, item.Date in @""

How can I do that?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
marnus
  • 11

4 Answers4

1

you should use $

$"{item.Account}, {item.Amount}, {item.Date}";

Because @ is used to escaping specials symbols

Darkk L
  • 889
  • 1
  • 4
  • 14
0

You won't be able to access item.* outside of foreach*.

To create a single string from multiple strings you could use string.Join:

List<string> l = new ();
foreach (var item in model.Transaction)
{
   var fromSingleItem = $"{item.Account}-{item.Amount}-{item.Date}";
   l.Append(fromSingleItem);
}
var fromAllItems = string.Join(", ", l);

* = What would time outside of foreach mean? Would it be the first item's data, or the last one's, or from the middle?

tymtam
  • 31,798
  • 8
  • 86
  • 126
0

I would use a string builder for this

 var sb= new StringBuilder();

foreach (var item in model.Transaction)
{
sb.Append( item.Account + "-" + item.Amount.ToString() + "-" 
+ item.Date.ToString() + "\n");
}

message.Body = new TextPart("plain")
{
     Text = sb.ToString();
};

or if you have only several items

var sb= string.Empty;

foreach (var item in model.Transaction)
{
sb+= item.Account + "-" + item.Amount.ToString() + "-" + item.Date.ToString() + "\n");
}
Serge
  • 40,935
  • 4
  • 18
  • 45
0

Serge has the right idea, but I would tweak it a bit as there is a performance penalty every time you concatenate using the '+' symbol (a new String object is instantiated when you concatenate with '+'). I would suggest you continue to use StringBuilder even if you only have a single item in your foreach loop.

var builder = new StringBuilder();
foreach (var item in model.Transaction)
{
    builder.Append(item.Account);
    builder.Append("-");
    builder.Append(item.Amount);
    builder.Append("-");
    builder.AppendLine(item.Date);
}

message.Body = new TextPart("plain")
{
    Text = builder.ToString()
};
CrossBound
  • 56
  • 5