3

I have a collection of Car objects,

IEnumerable<Car>

And I want to return a filtered collection of car objects, based on a partial string match (it doesn't have to be startswith) where the Car.Name property has certain text in it.

Is this possible using LINQ?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
leora
  • 188,729
  • 360
  • 878
  • 1,366
  • Instead of string.Contains, you could use IndexOf if you want a case-insensitive search, so you can pass a StringComparison value. See http://stackoverflow.com/questions/444798/case-insensitive-containsstring – Peter Feb 21 '11 at 12:13

4 Answers4

6
from c in cars
where c.Name.Contains("certain text")
select c

or

cars.Where(c => c.Name.Contains("certain text"))
Stilgar
  • 22,354
  • 14
  • 64
  • 101
1
IEnumerable<Car> cars = ...
var filteredCars = cars.Where(car => car.Name.Contains("your text"));
Albin Sunnanbo
  • 46,430
  • 8
  • 69
  • 108
1

You can use Contains:

var cars = new List<Car>(); //Or whatever makes sense.

var filteredCars = cars.Where(c => c.Name.Contains("searchstring"));
Klaus Byskov Pedersen
  • 117,245
  • 29
  • 183
  • 222
0

This may do what you want:

var filteredCars = cars.Where(car => car.Name.Contains("Fiesta"));

You can increase the complexity of the predicate as you wish.

Andy Holt
  • 572
  • 2
  • 9