开发者

How to check for empty item in a generic list

Assert.IsTrue(benefits.Count(P => string.IsN开发者_开发技巧ullOrEmpty(P.bCode)) > 0);

HEre benefits is list of objects of type Obj...which has one property bCode.

I want to check if all items in list benefits has "bCode"...not null and not empty.


benefits.All(b => !String.IsNullOrEmpty(b.bCode));

You can read about Enumerable.All on MSDN. Note that it exhibits "short-circuiting" behavior like && (which is what it is analogous to). You can wrap this is in Assert.IsTrue if you so desire for your test runner.

You should seriously consider renaming bCode to BenefitCode, assuming that is what it stands for. There is no reason to not use meaningful business names. Your ORM can handle it.


Assert.IsTrue(!benefits.Any(p => string.IsNullOrEmpty(p.bCode)));


Try this:

benefits.TrueForAll(P=> !string.IsNullOrEmpty(P.bCode))


.net 2.0 version:

List<Obj> findResults = benefits.FindAll((Predicate<string>)delegate(Obj item)
{
    return !string.IsNullOrempty(item.bCode);
});

return findResults.Count == benefits.Count;


If I understand you correctly, you want to ensure that no bCode property within benefits is null or empty? Does the code you provided not work? How about this:

Assert.IsTrue(benefits.Where(b => string.IsNullOrEmpty(b.bCode)).Count() == 0);


If you also want to ensure that each benefits item is not null (which your question does not specify), you can use this:

Assert.IsTrue(!benefits.Any(p => p == null || string.IsNullOrEmpty(p.bCode)));


Small correct use .Trim() This will work in ideal situation however in the following case it will not work

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

Use

        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

I would suggest to use

Assert.IsTrue(!benefits.Any(p => string.IsNullOrEmpty(p.bCode.Trim()))); // for better result

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜