How to convert DateTime? to String directly (in c# linq) - c#

i'm making a web-service where i'm calling data-objects who are created directly through linq, i was wondering, how i can convert DateTime? directly to string?, this, because i can't convert the DateTime? to DateTime and then to string through a variable or a what not, because linq don't let me.
Here's the code:
lista = (from p in db.Acciones
select new ItemAcciones
{
ID_Accion = p.ID_Accion,
FechaHora = p.FechaHora != null ? (DateTime)p.FechaHora : DateTime.Now,
//ShowFechaHora = !String.IsNullOrWhiteSpace(((DateTime)p.FechaHora).ToString("HH:mm")) ? ((DateTime)p.FechaHora).ToString("HH:mm") : DateTime.Now.ToString("HH:mm"),
ID_EmpresaNombre = p.Empresas.EmpresaNombre,
ID_ResponsableNombre = p.Responsables.LoginID,
ID_ContactoNombre = p.Contactos.Nombres + " " + p.Contactos.Paterno + " " + p.Contactos.Materno,
ID_AccionTipoNombre = p.AccionTipos.AccionTipoGlosa,
ID_AccionEstadoNombre = p.AccionEstados.AccEstGlosa,
AccionGlosa = p.AccionGlosa,
ID_Empresa = p.ID_Empresa,
AccionDescripcion = p.AccionDescripcion,
ID_Negocio = (int?)p.ID_Negocio ?? 0,
ID_Contacto = p.ID_Contacto,
ID_AccionTipo = p.ID_AccionTipo,
ID_AccionEstado = p.ID_AccionEstado,
ID_ProgFecha = p.ID_ProgFecha != null ? (int)p.ID_ProgFecha : 0,
ShowID_ProgFecha = String.IsNullOrWhiteSpace(p.ID_ProgFecha.ToString()) ?? p.ID_ProgFecha.ToString() : "--/--/----",
//ShowID_ProgFecha = StringAEstilizarComoDate(Convert.ToString(p.ID_ProgFecha)),
ID_ProgHora = p.ID_ProgHora != null ? (int)p.ID_ProgHora : 0,
//ShowID_ProgHora = StringAEstilizarComoHora(Convert.ToString(p.ID_ProgHora)),
ID_EjecFecha = p.ID_EjecFecha != null ? (int)p.ID_EjecFecha : 0,
//ShowID_EjecFecha = StringAEstilizarComoDate(Convert.ToString(p.ID_EjecFecha)),
ID_EjecHora = p.ID_EjecHora != null ? (int)p.ID_EjecHora : 0,
//ShowID_EjecHora = StringAEstilizarComoHora(Convert.ToString(p.ID_EjecHora)),
ID_Responsable = p.ID_Responsable,
EmpresaRUTCompleto = p.Empresas.EmpresaRut.ToString() + "-" + p.Empresas.EmpresaDV,
ID_NegocioNombre = p.Negocios.ProyectoNombre,
}).ToList();
Any question, suggestion or comment to improve the question would be appreciated as well as the answer.

It's a manually solution, but you can use SqlFunctions to handle the string for your Date.
var qqqq = db.YourTable.Select(q => (q.YourDate == null ? "" : (SqlFunctions.DateName("day",q.YourDate) + "/" + SqlFunctions.DateName("month", q.YourDate) + "/" + SqlFunctions.DateName("year", q.YourDate) + " " + SqlFunctions.DateName("hour", q.YourDate) + " " + SqlFunctions.DateName("minute", q.YourDate)))).ToList();
Hope that helps. =)

Related

Why does adding a WHERE clause make this untranslatable?

The following works just fine:
myStatements = db.Statements.Select(s => new StatementModel
{
StatmentId = s.StatementId,
EmployeeNumber = s.EmployeeNumber,
FirstName = s.Employee.FirstName,
LastName = s.Employee.LastName,
PlanVariantType = s.Employee.PlanVariantType != null ? s.Employee.PlanVariantType.PlanVariantTypeName : "",
FiscalPeriod = s.FiscalPeriod != null ? s.FiscalPeriod.FiscalPeriodName : "",
CostCenterId = s.Employee.CostCenterId,
EVPName = s.Employee.CostCenter.Evp != null ? s.Employee.CostCenter.Evp.FirstName + " " + s.Employee.CostCenter.Evp.LastName : "",
SVPName = s.Employee.CostCenter.Svp != null ? s.Employee.CostCenter.Svp.FirstName + " " + s.Employee.CostCenter.Svp.LastName : "",
LOBMgrName = s.Employee.CostCenter.Lobmgr != null ? s.Employee.CostCenter.Lobmgr.FirstName + " " + s.Employee.CostCenter.Lobmgr.LastName : "",
AdminApprovalStatus = s.AdminApprovalStatus.ApprovalStatusName,
StatementStatus = s.StatementStatus.StatementStatusName,
AmountDue = s.AmountDue
}).ToList();
But if I add a simple WHERE clause it throws an exception saying it can't be translated:
myStatements = db.Statements.Select(s => new StatementModel
{
StatmentId = s.StatementId,
EmployeeNumber = s.EmployeeNumber,
FirstName = s.Employee.FirstName,
LastName = s.Employee.LastName,
PlanVariantType = s.Employee.PlanVariantType != null ? s.Employee.PlanVariantType.PlanVariantTypeName : "",
FiscalPeriod = s.FiscalPeriod != null ? s.FiscalPeriod.FiscalPeriodName : "",
CostCenterId = s.Employee.CostCenterId,
EVPName = s.Employee.CostCenter.Evp != null ? s.Employee.CostCenter.Evp.FirstName + " " + s.Employee.CostCenter.Evp.LastName : "",
SVPName = s.Employee.CostCenter.Svp != null ? s.Employee.CostCenter.Svp.FirstName + " " + s.Employee.CostCenter.Svp.LastName : "",
LOBMgrName = s.Employee.CostCenter.Lobmgr != null ? s.Employee.CostCenter.Lobmgr.FirstName + " " + s.Employee.CostCenter.Lobmgr.LastName : "",
AdminApprovalStatus = s.AdminApprovalStatus.ApprovalStatusName,
StatementStatus = s.StatementStatus.StatementStatusName,
AmountDue = s.AmountDue
}).Where(s => s.StatementStatusId == "PAA").ToList();
The exception message is a mess and isn't helpful beyond telling me that it couldn't be translated.
So what's the issue with the WHERE clause?
Try this. Use where clause first then projection.
myStatements = db.Statements.Where(s => s.StatementStatusId == "PAA").Select(s => new StatementModel
{
StatmentId = s.StatementId,
EmployeeNumber = s.EmployeeNumber,
FirstName = s.Employee.FirstName,
LastName = s.Employee.LastName,
PlanVariantType = s.Employee.PlanVariantType != null ? s.Employee.PlanVariantType.PlanVariantTypeName : "",
FiscalPeriod = s.FiscalPeriod != null ? s.FiscalPeriod.FiscalPeriodName : "",
CostCenterId = s.Employee.CostCenterId,
EVPName = s.Employee.CostCenter.Evp != null ? s.Employee.CostCenter.Evp.FirstName + " " + s.Employee.CostCenter.Evp.LastName : "",
SVPName = s.Employee.CostCenter.Svp != null ? s.Employee.CostCenter.Svp.FirstName + " " + s.Employee.CostCenter.Svp.LastName : "",
LOBMgrName = s.Employee.CostCenter.Lobmgr != null ? s.Employee.CostCenter.Lobmgr.FirstName + " " + s.Employee.CostCenter.Lobmgr.LastName : "",
AdminApprovalStatus = s.AdminApprovalStatus.ApprovalStatusName,
StatementStatus = s.StatementStatus.StatementStatusName,
AmountDue = s.AmountDue
}).ToList();
Problem here that you have custom projection. It means that LINQ translator knows only fields which are explicitly mapped. StatementStatusId has no mapping and Translator throws error. Add mapping and query will work:
myStatements = db.Statements.Select(s => new StatementModel
{
StatmentId = s.StatementId,
EmployeeNumber = s.EmployeeNumber,
FirstName = s.Employee.FirstName,
LastName = s.Employee.LastName,
PlanVariantType = s.Employee.PlanVariantType != null ? s.Employee.PlanVariantType.PlanVariantTypeName : "",
FiscalPeriod = s.FiscalPeriod != null ? s.FiscalPeriod.FiscalPeriodName : "",
CostCenterId = s.Employee.CostCenterId,
EVPName = s.Employee.CostCenter.Evp != null ? s.Employee.CostCenter.Evp.FirstName + " " + s.Employee.CostCenter.Evp.LastName : "",
SVPName = s.Employee.CostCenter.Svp != null ? s.Employee.CostCenter.Svp.FirstName + " " + s.Employee.CostCenter.Svp.LastName : "",
LOBMgrName = s.Employee.CostCenter.Lobmgr != null ? s.Employee.CostCenter.Lobmgr.FirstName + " " + s.Employee.CostCenter.Lobmgr.LastName : "",
AdminApprovalStatus = s.AdminApprovalStatus.ApprovalStatusName,
StatementStatus = s.StatementStatus.StatementStatusName,
AmountDue = s.AmountDue,
// missing mapping
StatementStatusId = s.StatementStatusId
}).Where(s => s.StatementStatusId == "PAA").ToList();

Nested Linq conversion (select)

Im trying to convert an object (Lead) to a reduced form of the same object (ApiLead)
The object contains a list of objects (OtherInHousehold) which also needs to be reduced (ApiOtherInHousehold):
result = leads.Select(lead => new ApiLead()
{
UserId = lead.UserId,
DepartmentId = lead.DepartmentId,
CompanyId = lead.CompanyId,
CPR_number = lead.CPR_number,
CVR_number = lead.CVR_number,
Name = (lead.FirstName == "[virksomhed]" ? "" : lead.FirstName + " ") + lead.LastName,
Address = (lead.Street + " " + lead.StreetNumber + " " + lead.Floor + " " + lead.Side).Trim(),
Zipcode = lead.Zipcode,
City = (lead.PlaceName + " " + lead.City).Trim(),
Phonenumber = ("Fastnet: " + lead.Phonenumber + " Mobil: " + lead.Cellphonenumber),
Email = lead.Email,
BestReached = lead.BestReached,
**OthersInHousehold = lead.OthersInHousehold.Select(oih => new ApiOtherInHousehold(){ CPR_number = oih.CPR_number, Name = oih.Name }).ToList()**,
WantsVisit = lead.WantsVisit,
WantsPhonecall = lead.WantsPhonecall,
WantsInsuranceImmediately = lead.WantsInsuranceImmediately,
ExistingInsurance = lead.ExistingInsurance,
CurrentInsuranceCompany = lead.CurrentInsuranceCompany,
OtherInfo = lead.OtherInfo,
Status = lead.Status,
CreationDate = lead.CreationDate
}).ToList();
But this throws an
Cannot implicitly convert type 'System.Collections.Generic.List<LeadsApp.ApiModels.ApiLead>' to
'System.Collections.Generic.List<LeadsApp.Models.Lead>'
Is this not possible or am I doing it wrong?
Thanks, guys.
At the linq statement, you are returning List<ApiLead>. But result variable is List<Lead>. You have to declare your result variable as List<ApiLead>.
Hope helps,

Make a string bold that is displayed in both a RadGrid txtNote and a label

I have a RadGrid that shows a txtNote as text in its note column. I also have a label called lblShowAllSessionNotes. When A session note is added or appended to an existing note, a type of ID stamp preceeds the actual txt message, like so:
NoteTYPE - CommunicationType - ContactType
Electronically signed by: someone's Name 6/12/2016 12:00:00
This is the note text. It is text.
If I put ... in the string variable in code behind, then in the radGrid it appears as: Electronically signed by: someone's name; instead of Electronically signed by: someone's name.... In the label it appears bold as expected.
I have a method:
/// <summary>
/// Creates and shows all session notes in a text format.
/// </summary>
protected void ShowAllSessionNotes()
{
var allNotes = new StringBuilder();
string splitStr = "";
string[] newStr = null;
foreach (var noteItem in SessionNotes())
{
allNotes.Append("<b>" + noteItem.DmSessionNoteType + " - </b>");
allNotes.Append("<b>" + noteItem.DmCommunicationType + " - </b>");
allNotes.Append("<b>" + noteItem.DmContactType + " - </b>");
allNotes.Append(noteItem.AddDateTime + " (CST)");
if (ShowDuration)
{
allNotes.AppendFormat(" - <b>Duration:</b> {0} - <b>Electronically signed by: </b> {1}",
FormatDuration(noteItem.Duration), noteItem.CCName);
}
if (noteItem.Note.Contains('|'))
{
splitStr = noteItem.Note;
newStr = splitStr.Split('|');
noteItem.Note = String.Join("<br/>", newStr);
}
if (noteItem.Note.Contains(':') && noteItem.Note.StartsWith("Electronically"))
{
splitStr = noteItem.Note;
string bldStr = splitStr.Split(':')[0];
}
allNotes.Append("<br />");
allNotes.Append(noteItem.Note);
allNotes.Append("<br /><br />");
}
lblShowAllSessionNotes.Text = allNotes.ToString();
lblShowAllSessionNotes.Visible = true;
}
and another....
/// <summary>
/// Helper function that populates a session note entity.
/// </summary>
/// <param name="item">The GridEditableItem to pull data from.</param>
/// <param name="sessionNote">Existing PatientSessionNote entity.</param>
/// <returns>Returns a populated PatientSessionNote entity.</returns>
private PatientSessionNote PopulatePatientSessionNote(GridEditableItem item, ref List<string> errors)
{
var id = item.ItemIndex != -1 ? Convert.ToInt32(item.OwnerTableView.DataKeyValues[item.ItemIndex]["ID"]) : 0;
var rcb = item.FindControl("radCmbNoteType") as RadComboBox;
var rcbCC = item.FindControl("radCmbCommunicationType") as RadComboBox;
var rcbC = item.FindControl("radCmbContactType") as RadComboBox;
var rtb = item.FindControl("rtbNote") as RadTextBox;
string userSign = "Electronically signed by: ";
var appendDate = DateTime.Now;
var appendUser = User.Identity.Name;
var appendName = new MasterBLL().getUserName(appendUser);
var origSessNote = item.FindControl("HideOriginalSessionNote") as HiddenField;
string sessionNoteSent = "";
if (origSessNote.Value == "".Trim() || origSessNote == null)
{
sessionNoteSent = rtb.Text;
}
else
{
sessionNoteSent = origSessNote.Value + " | " + Environment.NewLine + userSign + appendName + " " + appendDate.ToString() + " | " + Environment.NewLine + rtb.Text;
}
var sessionNote = new PatientSessionNote
{
Id = id,
PatientId = _patientId,
DeleteReason = string.Empty,
IsDeleted = false,
LastUpdateDateTime = DateTime.Now,
LastUpdateUserName = CurrentUserId,
CommunicationTypeId = Convert.ToInt32(rcbCC.SelectedValue),
ContactTypeId = Convert.ToInt32(rcbC.SelectedValue),
SessionNoteTypeId = Convert.ToInt32(rcb.SelectedValue),
Note = Server.HtmlDecode(sessionNoteSent)
};
if (id == 0)
{
sessionNote.AddDateTime = DateTime.Now;
sessionNote.AddUserName = CurrentUserId;
}
if (ShowDuration)
{
var rdpSessionDate = item.FindControl("rdpSessionDate") as RadDatePicker;
var txtSessionStartTime = item.FindControl("txtSessionStartTime") as TextBox;
var txtSessionEndTime = item.FindControl("txtSessionEndTime") as TextBox;
//Set any existing values to NULL (for UPDATEs) so that validation doesn't allow incorrect inputs because of pre-existing old values
//This values will be redefined thru the standard INSERT practices
sessionNote.SessionStart = null;
sessionNote.SessionEnd = null;
sessionNote.Duration = 0;
if (rdpSessionDate != null && txtSessionStartTime != null && txtSessionEndTime != null)
{
var regexDate = Regex.Match(rdpSessionDate.DbSelectedDate.ToString(), #"\d{1,2}/\d{1,2}/\d{4}",
RegexOptions.Singleline);
if (regexDate.Success)
{
var startTime = Regex.Match(txtSessionStartTime.Text,
#"(?i)(?<Hours>\d{1,2}):(?<Minutes>\d{2})(?<Meridian>am|pm)", RegexOptions.Singleline);
var endTime = Regex.Match(txtSessionEndTime.Text,
#"(?i)(?<Hours>\d{1,2}):(?<Minutes>\d{2})(?<Meridian>am|pm)", RegexOptions.Singleline);
if (startTime.Success && endTime.Success)
{
//SessionStart & SessionEnd Dates
DateTime varDate;
if (DateTime.TryParse(rdpSessionDate.DbSelectedDate.ToString(), out varDate))
{
var startHours = int.Parse(startTime.Groups["Hours"].Value)%12;
var endHours = int.Parse(endTime.Groups["Hours"].Value)%12;
var startMinutes = int.Parse(startTime.Groups["Minutes"].Value);
var endMinutes = int.Parse(endTime.Groups["Minutes"].Value);
var isStartAM = Regex.IsMatch(startTime.Groups["Meridian"].Value.ToLower(), "am");
var isEndAM = Regex.IsMatch(endTime.Groups["Meridian"].Value.ToLower(), "am");
if (varDate != DateTime.MinValue)
{
var startDate = new DateTime(varDate.Year, varDate.Month, varDate.Day,
((isStartAM) ? startHours : (startHours + 12)), startMinutes, 0);
var endDate = new DateTime(varDate.Year, varDate.Month, varDate.Day,
((isEndAM) ? endHours : (endHours + 12)), endMinutes, 0);
var span = endDate.Subtract(startDate);
sessionNote.SessionStart = startDate;
if (span.TotalMinutes > 0)
//Only log if the amount of minutes is a positive number (integer)
{
sessionNote.SessionEnd = endDate;
sessionNote.Duration = (int) span.TotalMinutes;
}
else
{
errors.Add(#"The start time is greater than the end time");
errors.Add(#"Date chosen: " + rdpSessionDate.DbSelectedDate);
errors.Add(#"Start date time: " + startDate);
errors.Add(#"End date time: " + endDate);
errors.Add(#"Total minutes: " + span.TotalMinutes);
}
}
else
{
errors.Add(#"Invalid date format: " + rdpSessionDate.DbSelectedDate);
}
}
else
{
errors.Add(#"Invalid date format: " + rdpSessionDate.DbSelectedDate);
}
}
else
{
if (!startTime.Success)
{
errors.Add(#"Invalid start time format: " + txtSessionStartTime.Text);
}
if (!endTime.Success)
{
errors.Add(#"Invalid end time format: " + txtSessionEndTime.Text);
}
}
}
else
{
errors.Add(#"Invalid date format: " + rdpSessionDate.DbSelectedDate);
}
}
else
{
if (rdpSessionDate == null)
{
errors.Add(#"RadDatePicker ControlID ""rdpSessionDate"" could not be found");
}
if (txtSessionStartTime == null)
{
errors.Add(#"TextBox ControlID ""txtSessionStartTime"" could not be found");
}
if (txtSessionEndTime == null)
{
errors.Add(#"TextBox ControlID ""txtSessionEndTime"" could not be found");
}
}
}
if (errors.Count > 0)
{
errors.Add("Server date: " + DateTime.Today);
}
return sessionNote;
}
If I put the bold tag < b > in the second method PopulatePatientSessionNote(...) on string userSign then it works for the label but not for the grid. I appreciate the help!
Ok because of time constraints I've done this: It's messy but it works.
I first added a property:
public string UserSign { get; set; }
In The PopulatePatientSessionNote(...) method I added this:
UserSign = "" + userSign + "";
sessionNoteSent = origSessNote.Value + " | " + Environment.NewLine + "`" + appendName + " " + appendDate.ToString() + " | " + Environment.NewLine + rtb.Text;
Then in the ShowAllSessionNotes (...) method I added:
splitStr = noteItem.Note;
newStr = splitStr.Split('`');
noteItem.Note = String.Join(UserSign, newStr);
It's messy but it works. Does anyone one have a better idea? Thx a bunch!!!

drop down comboBox if else statement error [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
If I write in cmbGrNo.text then there will be an
Input string is not in correct format
How can I identify that which combobox is edit?
I write in combobox and then click on search button the compiler is giving me error cause it does not accept the other combobox text. It only accepts the value of first one ...
please help me
HERE IS THE CODE
private void btnSearch_Click(object sender, EventArgs e)
{
if (cmbAdmissionNo.Text.Length == 0 && cmbRollNo.Text.Length == 0 && cmbStudentName.Text.Length == 0 && cmbGRNo.Text.Length == 0)
{
MessageBox.Show("Enter Student Name OR Admission No OR Gr No OR Roll No"," INSERT FIELDS", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
if (StudentDBClass.CheckStudent(cmbStudentName.Text))
{
DataTable dt = StudentDBClass.getTableBYStdName(cmbStudentName.Text);
txtAdminNo.Text = "Admission No : " + dt.Rows[0]["AddmissionNo"];
txtGrNo.Text = "GR No : " + dt.Rows[0]["GRNo"];
txtClass.Text = "Class : " + dt.Rows[0]["ClassName"];
txtStudentName.Text = "Student Name : " + dt.Rows[0]["StudentName"];
txtFatherName.Text = "Father Name : " + dt.Rows[0]["FatherName"];
txtRollNo.Text = "Roll No: " + dt.Rows[0]["RollNo"];
dgvStdFeeCollection.DataSource = null;
dgvStdFeeCollection.DataSource = StudentFeeCollectionDBClass.getStdNameForDgvFeeCollection(cmbStudentName.Text);
cmbAdmissionNo.SelectedIndex = -1;
cmbGRNo.SelectedIndex = -1;
cmbRollNo.SelectedIndex = -1;
cmbAdmissionNo.Text = string.Empty;
cmbGRNo.Text = string.Empty;
cmbRollNo.Text = string.Empty;
}
else if (StudentDBClass.CheckWithAdmissionNo(Convert.ToInt32(cmbAdmissionNo.Text)))
{
DataTable dt = StudentDBClass.getTableBYAddmissionNo(Convert.ToInt32(cmbAdmissionNo.Text));
txtAdminNo.Text = "Admission No : " + dt.Rows[0]["AddmissionNo"];
txtGrNo.Text = "GR No : " + dt.Rows[0]["GRNo"];
txtClass.Text = "Class : " + dt.Rows[0]["ClassName"];
txtStudentName.Text = "Student Name : " + dt.Rows[0]["StudentName"];
txtFatherName.Text = "Father Name : " + dt.Rows[0]["FatherName"];
txtRollNo.Text = "Roll No: " + dt.Rows[0]["RollNo"];
dgvStdFeeCollection.DataSource = null;
dgvStdFeeCollection.DataSource = StudentFeeCollectionDBClass.getAdmissionNoForDgvFeeCollection(Convert.ToInt32(cmbAdmissionNo.Text));
cmbStudentName.SelectedIndex = -1;
cmbGRNo.SelectedIndex = -1;
cmbRollNo.SelectedIndex = -1;
cmbGRNo.Text = string.Empty;
cmbStudentName.Text = string.Empty;
cmbRollNo.Text = string.Empty;
}
else if (StudentDBClass.CheckGRNo(Convert.ToInt32(cmbGRNo.Text)))
{
DataTable dt = StudentDBClass.getTableGrNo(Convert.ToInt32(cmbGRNo.Text));
txtAdminNo.Text = "Admission No : " + dt.Rows[0]["AddmissionNo"];
txtGrNo.Text = "GR No : " + dt.Rows[0]["GRNo"];
txtClass.Text = "Class : " + dt.Rows[0]["ClassName"];
txtStudentName.Text = "Student Name : " + dt.Rows[0]["StudentName"];
txtFatherName.Text = "Father Name : " + dt.Rows[0]["FatherName"];
txtRollNo.Text = "Roll No: " + dt.Rows[0]["RollNo"];
dgvStdFeeCollection.DataSource = null;
dgvStdFeeCollection.DataSource = StudentFeeCollectionDBClass.getGrNoForDgvFeeCollection(Convert.ToInt32(cmbGRNo.Text));
cmbAdmissionNo.SelectedIndex = -1;
cmbStudentName.SelectedIndex = -1;
cmbRollNo.SelectedIndex = -1;
cmbAdmissionNo.Text = string.Empty;
cmbStudentName.Text = string.Empty;
cmbRollNo.Text = string.Empty;
}
This error occurs when the Convert.ToInt32 receives a string that its not able to parse.
You are selecting the text value of the combobox, this will not return an integer.
You need to select the SelectedValue of the combobox.
Something like this:
Convert.ToInt32(cmbGrNo.SelectedValue.Text)

error: The query results cannot be enumerated more than once

Edit:
DataClassesDataContext dc = new DataClassesDataContext();
string _idCompany = Request["idCompany"];
var newes = dc.GetNewsCompany(Int64.Parse(_idCompany));
string date = "";
string newsHtml = "<center>";
if(newes.GetEnumerator().MoveNext()){
foreach (var item in newes)//say Error .......................
{
// date = calendar.GetDayOfMonth(item.DateSend) + "/" + calendar.GetMonth(item.DateSend) + "/" + calendar.GetYear(item.DateSend).ToString();
// newsHtml += "<li class='news-item'><a style='text-decoration:none' class=\"link\" onclick=\"$(\'#BodyNews\').text(\'" + HttpUtility.HtmlEncode(item.Body).Trim() + "\');$(\'#BodyNews\').dialog({resizable:false});\" href=\"#\" > " + item.Title.ToString() + "</a> " + date + " </li>";
}
newsHtml += "</center>";
}
else
{
// var propertyCompany = dc.GetPropertyCompanyById(Int64.Parse(_idCompany));
// newsHtml += "<li class='news-item'><a style='text-decoration:none' class=\"link\" );$(\'#BodyNews\').dialog({resizable:false});\" href=\"#\" > " + "!به صفحه شخصی شرکت " + propertyCompany.FirstOrDefault().NameCompany + " خوش آمدید " + "</a> " + date + " </li>";
}
return newsHtml;
say error:The query results cannot be enumerated more than once
how check var is empty or null with out enumerated;
Why bother with the if at all?
var newes = dc.GetNewsCompany(Int64.Parse(_idCompany));
//if (newes.GetEnumerator().MoveNext())//check is null or empty
var newesList = newes.ToList();
if (neweList.Count > 0)
{
...
}
You can always check the newesList.Count property afterward.
Not sure what's available as a member in newes, but if it's an object and depending on what dc.GetNewsCompany returns you could check for null
if (news == null) return;
or if it returns an empty collection/array, just check the count/length:
if (news.Count == 0) return;
if (news.Length == 0) return;
the error comes, because you are using .GetEnumerator() on newes and then using the newes again in a foreach Loop .. this causes the "double enumeration".
Generally avoid walking "such var"'s with a foreach, since the DataReader is locked the whole loop !. Means that you cannot use the same entitie in this loop.
Better .ToList() , you can the list.AsQuearable agian if you want to Linq on it
f.e. something like
var newes = dc.CompanyTable.Where(ln => ln.id.Equals(_idCompany));;
List<CompanyTable> newesList = newes.ToList();

Categories