I have a class House
, and I create a List<House>
with some new Houses. Now I would like to filter my List' where the Name of the House equals
"House 1"`.
How should I handle this situation?
I tried houses.FindAll("House 1");
but this showed the error:
Argument 1: cannot convert from 'string' to System.Predicate <"App.Page1.House">
class House
{
public House(string name, string location)
{
this.Name = name;
this.Location = location;
}
public string Name { private set; get; }
public string Location { private set; get; }
};
//TODO: fill this with data from the database
List<House> houses= new List<House>
{
new House("House 1", "Location 1"),
new House("House 2", "Location 4"),
new House("House 3", "Location 3"),
new House("House 4", "Location 2")
};
C# filter list with FindAll. In the following example, we filter a list with the built-in FindAll method. var vals = new List<int> {-1, -3, 0, 1, 3, 2, 9, -4}; List<int> filtered = vals. FindAll(e => e > 0); Console.
List in C# is a collection of strongly typed objects. These objects can be easily accessed using their respective index. Index calling gives the flexibility to sort, search, and modify lists if required.
The get keyword defines an accessor method in a property or indexer that returns the property value or the indexer element. For more information, see Properties, Auto-Implemented Properties and Indexers.
Python has a built-in function called filter() that allows you to filter a list (or a tuple) in a more beautiful way. The filter() function iterates over the elements of the list and applies the fn() function to each element. It returns an iterator for the elements where the fn() returns True .
The problem you are having is that you have to give FindAll
a predicate. You can do that with a lambda
List<House> houseOnes = houses.FindAll(house => house.Name == "House 1");
Basically you have to tell it what you want to compare to for each item. In this case you compare the Name
property to the string
value you are interested in.
Another alternative is to use Linq
List<House> houseOnes = houses.Where(house => house.Name == "House 1").ToList();
Note here you have to call ToList
in order to get a list. Without that you'd have an IEnumerabl<House>
and it wouldn't actually do the comparisons until you iterated it (which the ToList
does). This is known as deferred execution and if your original houses
list changed before you iterated it you could get different result, which may or may not be desirable. By calling ToList
you ensure that your results will reflect the state of your list when you make that call.
Use Linq:
List<House> houseOnes = houses.Where(house => house.Name == "House 1").ToList();
or if there is only 1 you hope to find
House houseOne = houses.SingleOrDefault(house => house.Name == "House 1");
and check the result for null to make sure you found it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With