How to return the first 50 characters of text in a LINQ call

I have a little winapp that uses LinqToSQL as a DAL. I am creating a summary overview of all CaseNotes for this person, and one of the fields is the Details window. I need to return only the first 50 characters of this column in my treeview function.

Any hints on how I do this? The following shows how my TreeView function gets its data to display, and ContactDetails is a column.

public static DataTable GetTreeViewCNotes(int personID) { var context = new MATRIXDataContext(); var caseNotesTree = from cn in context.tblCaseNotes where cn.PersonID == personID orderby cn.ContactDate select new { cn.CaseNoteID,cn.ContactDate, cn.ParentNote, cn.IsCaseLog, cn.ContactDetails }; var dataTable = caseNotesTree.CopyLinqToDataTable(); context.Dispose(); return dataTable; } 

ANSWER

I post it here if future search engines are wondering what the solution looks like in the context of the questions.

  public static DataTable GetTreeViewCNotes(int personID) { DataTable dataTable; using (var context = new MATRIXDataContext()) { var caseNotesTree = from cn in context.tblCaseNotes where cn.PersonID == personID orderby cn.ContactDate select new { cn.CaseNoteID, cn.ContactDate, cn.ParentNote, cn.IsCaseLog, ContactDetailsPreview = cn.ContactDetails.Substring(0,50) }; dataTable = caseNotesTree.CopyLinqToDataTable(); } return dataTable; } 
+6
c # winforms linq-to-sql
source share
3 answers

String.Substring :

 var caseNotesTree = from cn in context.tblCaseNotes where cn.PersonID == personID orderby cn.ContactDate select new { cn.CaseNoteID, cn.ContactDate, cn.ParentNote, cn.IsCaseLog, ContactDetailsClip = cn.ContactDetails.Substring(0, Math.Min(cn.ContactDetails.Length, 50)) }; 

In addition, I would suggest wrapping the use of DataContext s in using .

+10
source share

With LinQ, you can also do the following:

 new string( myString.Take(50).ToArray() ); 
+4
source share
 cn.ContactDetails.Substring(0, 50); 

In the line "select new". It works?

0
source share

All Articles