Search code examples
c#winformslinq-to-sql

How to return first 50 characters of text in LINQ call


I have a small winapp that uses LinqToSQL as it's DAL. I am creating a summary view of all the CaseNotes for a given person and one of the fields is a Details box. I need to return only the first 50 characters of that column to my treeview function.

Any hints on how I do that? The below is how my TreeView function gets its data for display and the ContactDetails is the column in question.

        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 am posting this here in case any future searchers wonder what the solution looks like in the questions context.

        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;
    }

Solution

  • 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))
                        };
    

    Also, I would suggest wrapping your use of DataContexts in using blocks.