简体   繁体   中英

How to check for empty item in a generic list

Assert.IsTrue(benefits.Count(P => string.IsNullOrEmpty(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.

Assert.IsTrue(!benefits.Any(p => string.IsNullOrEmpty(p.bCode)));
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.

尝试这个:

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);

如果您还想确保每个福利项不为空(您的问题没有指定),您可以使用:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM