2016-02-11 45 views
-1
/*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); 

似乎很好地工作,如果沒有重複的日期時間被發現空性反應會觸發我的JavaScript保存。但是可以使用: if(!partReply.ToString()。IsNullOrEmpty()) 由於StringBuilder沒有自己的.IsNullOrEmpty()等價物嗎? 我能找到的每條評論,問題等都與Strings相關,並且無法在MSDN上看到任何內容!我可以一個StringBuilder對象上使用的ToString()。IsNullOrEmpty()以上

+0

那會更可靠? @DrewKennedy –

回答

2

在你的情況,partReply永遠不能爲null或空,因爲Enumerable.Aggregate拋出InvalidOperationException時,有沒有輸入元素。 你的代碼崩潰了。

在一般情況下,你可以用0 Length財產比較,例如:

if (partReply.Length > 0) 
+0

偉大的答案@jacob,並感謝我將使用它! –

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 
+0

「IsStringBuilderNullOrEmpty」的這個實現在每次調用時都會創建一個垃圾字符串。而不是轉換爲'string',查詢'Length'屬性。 –

+1

我最初是這樣做的,然後在StringBuilder是5個空白字符的情況下進行了更改,但我認爲這不是必需的。我會改回它。 –

相關問題