Search code examples
c#stringbuilder

StringBuilder Is not working When its under ForEach loop


Here I am Having Some names But name is not binding to String Builder

var x=from n in d.Employee
 Where n.EmpId==10
select n

 foreach (var master in x)
            {
                StringBuilder sb = new StringBuilder();
                StringBuilder abc = new StringBuilder();
                sb.Append(master.CANDIDATE_NAME + ",";
                abc.Append(sb);
                join_Body = new HrEmailsender()
                {
     Body = "Hi," + abc +                   
                };

Please Give me Appropriator hint for solving this issue


Solution

  • you are creating a new stringbuilder (sb, abc) in each loop but you want only one stringbuilder which something is added to in each loop, create the stringbuilders outside of the loop:

    var x=from n in d.Employee
         Where n.EmpId==10
        select n
    
                        StringBuilder sb = new StringBuilder();
                        StringBuilder abc = new StringBuilder();
    
         foreach (var master in x)
                    {
    
                        sb.Append(master.CANDIDATE_NAME + ",");
                        abc.Append(sb);
                        join_Body = new HrEmailsender()
                        {
             Body = "Hi," + abc +                   
                        };