Rod
Rod

Reputation: 15475

search my list help with linq

I have a

    list<fruitObj>


    Fruit
    FruitName, FruitColor
    banana, yellow
    orange, orange
    cherry, red

    List<FruitObj> test = new List<FruitObj>();

Is there an inline way of searching the list for starts with BAN and just return true if it does contain the string?

Upvotes: 0

Views: 158

Answers (6)

KP.
KP.

Reputation: 13720

var hasBAN = test.Any(fruit => fruit.FruitName.ToUpper().StartsWith("BAN"));

Upvotes: 0

Larry
Larry

Reputation: 18051

bool startsWithBan = test.Any(f => 
    f.Name.StartsWith("ban", StringComparison.InvariantCultureIgnoreCase));

Assuming Name is a property that contains the fruit name.

Upvotes: 3

Dustin Laine
Dustin Laine

Reputation: 38543

test.Where(fo => fo.FruitName.ToUpper().StartsWith("BAN"));

if (test.Count(fo => fo.FruitName.ToUpper().StartsWith("BAN")) > 0) 
{
    //... 
}

Upvotes: 0

n8wrl
n8wrl

Reputation: 19765

Lots of assumptions here...

IF a FruitObj has a .Name property that can be one of the names you listed, you could do this:

list.Any(f => f.Name.StartsWith("BAN"));

Upvotes: 0

Aliostad
Aliostad

Reputation: 81700

This does case insensitive:

 bool hasAnyBAN = test.Any(x=>x.StartsWith("BAN", StringCoparison.InvariantCultureIgnoreCase));

Upvotes: 3

BrokenGlass
BrokenGlass

Reputation: 161002

bool hasBAN = test.Any( x => x.FruitName.StartsWith("BAN"));

Note that this is case sensitive, to match "banana" you could do:

bool hasBAN = test.Any( x => x.FruitName.StartsWith("BAN", StringComparison.InvariantCultureIgnoreCase));

Upvotes: 4

Related Questions