Cooper Cripps
Cooper Cripps

Reputation: 205

c# - Searching for a combination within a list

I have the following:

public class Address{
    public string Number { get; set; }
    public string Street { get; set; }
    public string Suburb { get; set; }
}

List<Address> MyAddressList = new List<Address>();

Address MyAddress = new Address();
myAddress.Number = "5"
myAddress.Street = "Smith St"
myAddress.Suburb = "Smithsville"
MyAddressList.Add(MyAddress);

Address MyAddress2 = new Address();
myAddress2.Number = "10"
myAddress2.Street = "John St"
myAddress2.Suburb = "Johnsville"
MyAddressList.Add(MyAddress2);

string [] StreetToFind = new string {"Smith St"};
string [] SuburbToFind = new string {"Smithsville"};
string [] secondSuburbToFind = new string {"Johnsville"};

I want to search through this list and look for a combination of values and return a bool if the combination is found.

To start, I can search for an individual value in the Street Property:

bool StreetIsFound = MyAddressList.Select(x => x.Street).Intersect(StreetToFind).Any();

and the same for Suburb:

bool SuburbIsFind = = MyAddressList.Select(x => x.Suburb).Intersect(SuburbToFind).Any();

but I want to be able to search for both in a combination (bool StreetandSuburbFound)

so that if I searched for StreetToFind and SuburbToFind, StreetandSuburbFound would be true but would be false if searching for StreetToFind and secondSuburbToFind.

Upvotes: 1

Views: 548

Answers (2)

Charleh
Charleh

Reputation: 14012

Or the method chain version of p.s.w.g's code:

MyAddressList.Any(x => StreetToFind.Contains(x.Street) 
                       && SuburbToFind.Contains(x.Suburb))

(obviously tweak as neccessary with the Contains etc)

Upvotes: 1

p.s.w.g
p.s.w.g

Reputation: 149020

You can do this all with one call to Any. Like this

var isFound = MyAddressList.Any(x => StreetToFind.Contains(x.Street) && SuburbToFind.Contains(x.Suburb));

Or in query syntax

var isFound =
    (from x in MyAddressList
     where StreetToFind.Contains(x.Street)
        && SuburbToFind.Contains(x.Suburb)
     select x)
    .Any();

Upvotes: 5

Related Questions