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;
}
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;
}
string str = yourStringVariable. Substring(0,5);
To get the first n characters of a string, we can use the built-in Substring() method by passing the 0, n as arguments to it. Where 0 is the start index, n is the number of characters we need to get from the string. In the example above, we have passed 0, 3 as arguments to the Substring() method.
Solution 1. int id = 2; var item = lstData. FirstOrDefault(k => k.ID == id); if (item != null) { // use the Item object to read the properties. // your code here... }
string str = "AM0122200204"; string substr = str. Substring(str. Length - 3);
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 DataContext
s in using
blocks.
With LinQ you can also do the following :
new string( myString.Take(50).ToArray() );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With