How to filter a list with objects in C #?

I have a class Houseand I am creating List<House>with some new Houses. Now I would like to filter out my List' where the Name of the House equals"House 1".

How do I deal with this situation?

I tried houses.FindAll("House 1");, but this showed an error:

Argument 1: cannot be converted 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")
    };
+4
source share
2 answers

The problem you are facing is that you have to give a FindAllpredicate. You can do it with lambda

List<House> houseOnes = houses.FindAll(house => house.Name == "House 1");

, . Name string, .

Linq

List<House> houseOnes = houses.Where(house => house.Name == "House 1").ToList();

, ToList, . IEnumerabl<House>, , ( ToList). , houses , , . ToList, , .

+8

Linq:

List<House> houseOnes = houses.Where(house => house.Name == "House 1").ToList();

1,

House houseOne = houses.SingleOrDefault(house => house.Name == "House 1");

null, , .

+3

Source: https://habr.com/ru/post/1614457/


All Articles