简体   繁体   中英

How to add existing string array value with this code?

Variable.cs

 public string[] CcEmails { get; set; }

Mail.cs

  EDTO.CcEmails = dr["rsh_ccmail"].ToString().Split(';');

here i got two strings eg. xxxx@gmail.com ; yyy@gmail.com

MailProcess.cs

dataRPT1=get data from sql
EDTO.CcEmails = new string[dataRPT1.Rows.Count];
                    for (int i = 0; i < dataRPT1.Rows.Count; i++)
                    {
                        EDTO.CcEmails[i] = dataRPT1.Rows[i]["email_addr"].ToString();
                    }

Here i got list of string eg.aaa@gmail.com ...... I am try to add with existing but it add only new values..Anyone could help me..

I find the easiest way of doing this is to create a list, add items to the list, then use string.Join to create the new string.

var items = new List<string>();
for (int i = 0; i < dataRPT1.Rows.Count; i++)
{
    items.Add(dataRPT1.Rows[i]["email_addr"].ToString());
}

EDTO.CcEmails = string.Join(";", items);

Update after changed question:

If the type of the CcEmails is an array, the last line could be:

EDTO.CcEmails = items.ToArray();

I tend to use union, although that will remove duplicate entries. But to keep all entries you can use Concat on the array.

        var emailString = "me@test.com;you@test.com";
        string[] emails = emailString.Split(';');

        string[] emailsFromSQL = new string[3];
        emailsFromSQL[0] = "everyone@test.com";
        emailsFromSQL[1] = "everyone2@test.com";
        emailsFromSQL[2] = "everyone2@test.com";

        //No Duplicates
        var combined = emails.Union(emailsFromSQL).ToArray();

        //Duplicates
        var allCombined = emails.Concat(emailsFromSQL).ToArray();

Thanks

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM