Showing Notes using String.Join

2020-08-04 03:51发布

问题:

I have a textbox in which users can put their notes and then I am showing those notes on the right hand side in the same page. Now in my DB I have columns:

-UserName
-Notes

Now here is the code to get the notes using LINQ2SQL:

int getName = Int16.Parse(Session["Selected"].ToString());
var showNotes = from r in em.Test
               where r.Name == getName
               select r.Note;
var showUser = from r in em.Test
               where r.Name == getName
               select r.UserName;

tbShowNote.Text = String.Join(Environment.NewLine, showNotes);
tbShowNote.Text = String.Join(Environment.NewLine, showUser);

This one shows me the UserName but not the Note. I want to show something like this:

  1. This is a Test Note. -UserName1

回答1:

Just select notes and user name in one query, then do your formatting afterwards:

var showNotes = from r in em.Test
                where r.Name == getName
                select new { Name = r.UserName, Notes = r.Note }

var userNotes = showNotes.Select((x,i) => string.Format("{0}. {1}-{2}", 
                                                        i, 
                                                        x.Notes, 
                                                        x.Name));

tbShowNote.Text = String.Join(Environment.NewLine, userNotes );