/*Class definition*/
public class ConcreteClassModel : BaseModel
{
...
public bool IntersectsWith(ConcreteClassModel ccm)
{
ccm.StartDateDT = DateTime.Parse(ccm.StartDate);
ccm.EndDateDT = DateTime.Parse(ccm.EndDate);
this.StartDateDT = DateTime.Parse(this.StartDate);
this.EndDateDT = DateTime.Parse(this.EndDate);
return !(this.StartDateDT > ccm.EndDateDT || this.EndDateDT < ccm.StartDateDT);
}
}
/*Inside Controller Method*/
List<ConcreteClassModel> periods = LoadAllByParameters<ConcreteClassModel>(
ccm.CoverId, x => x.CoverId,
ccm.SectionId, x => x.SectionId);
var intersectingPeriods =
periods.Where(x => x.IntersectsWith(ccm));
StringBuilder partReply = intersectingPeriods.Aggregate(new StringBuilder(), (a, b) => a.Append(b));
********if (!partReply.ToString().IsNullOrEmpty())***************************
{
string reply =
"<div id='duplicateErrorDialog' title='Duplication Error'><span> Duplicate Period(s)</br>" +
partReply + "</span></ div >";
return Json(reply, JsonRequestBehavior.AllowGet);
}
return Json(null, JsonRequestBehavior.AllowGet);
以上似乎工作正常,如果没有找到重复的日期,null响应将触发我的javascript保存。但是可以使用: if(!partReply.ToString()。IsNullOrEmpty()) 由于StringBuilder没有自己的.IsNullOrEmpty()等价物? 我能找到的每个评论,问题等仅与字符串有关,在MSDN上看不到任何内容!
答案 0 :(得分:2)
在您的情况下,partReply
永远不能为空或空,因为Enumerable.Aggregate
在没有输入元素时会抛出InvalidOperationException
。 您的代码崩溃。
在一般情况下,您可以将Length
属性与0进行比较,例如:
if (partReply.Length > 0)
答案 1 :(得分:0)
您可以创建一个快速方法来帮助检查StringBuilder
对象是空还是空:
private bool IsStringBuilderNullOrEmpty(StringBuilder sb) {
return sb == null || sb.Length == 0);
}
//text examples
StringBuilder test = null;
Console.WriteLine(IsStringBuilderNullOrEmpty(test));//true
StringBuilder test = new StringBuilder();
test.Append("");
Console.WriteLine(IsStringBuilderNullOrEmpty(test));//true
StringBuilder test = new StringBuilder();
test.Append("hello there");
Console.WriteLine(IsStringBuilderNullOrEmpty(test));//false