[英]How to check for empty item in a generic list
Assert.IsTrue(benefits.Count(P => string.IsNullOrEmpty(P.bCode)) > 0);
HEre的好處是Obj類型的對象列表...它有一個屬性bCode。
我想檢查列表中的所有項目是否具有“bCode”...不為空且不為空。
Assert.IsTrue(!benefits.Any(p => string.IsNullOrEmpty(p.bCode)));
benefits.All(b => !String.IsNullOrEmpty(b.bCode));
您可以在MSDN上閱讀有關Enumerable.All
內容。 請注意,它表現出像&&
這樣的“短路”行為(這與它類似)。 你可以將它包裝在Assert.IsTrue
如果你想要你的測試運行器。
您應該認真考慮將bCode
重命名為BenefitCode
,假設它代表它的含義。 沒有理由不使用有意義的商業名稱。 您的ORM可以處理它。
嘗試這個:
benefits.TrueForAll(P=> !string.IsNullOrEmpty(P.bCode))
.net 2.0版本:
List<Obj> findResults = benefits.FindAll((Predicate<string>)delegate(Obj item)
{
return !string.IsNullOrempty(item.bCode);
});
return findResults.Count == benefits.Count;
如果我理解正確,您希望確保benefits
bCode
屬性為null或為空? 您提供的代碼不起作用嗎? 這個怎么樣:
Assert.IsTrue(benefits.Where(b => string.IsNullOrEmpty(b.bCode)).Count() == 0);
如果您還想確保每個福利項不為空(您的問題沒有指定),您可以使用:
Assert.IsTrue(!benefits.Any(p => p == null || string.IsNullOrEmpty(p.bCode)));
小正確使用.Trim()這將在理想情況下工作,但在下列情況下它將無法正常工作
Assert.IsTrue(!benefits.Any(p => string.IsNullOrEmpty(p.bCode)));
string[] input = new[] {"A", "", "B"," ", "C", "D"};
int count = input.Count(i => string.IsNullOrEmpty(i));
Console.WriteLine(count); // Result will be 1 now which is incorrect
采用
string[] input = new[] {"A", "", "B"," ", "C", "D"};
int count = input.Count(i => string.IsNullOrEmpty(i.Trim()));
Console.WriteLine(count); // Result will be 2 now which is correct
我建議使用
Assert.IsTrue(!benefits.Any(p => string.IsNullOrEmpty(p.bCode.Trim()))); //為了更好的結果
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.