1

我有以下内容:

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"};

我想搜索此列表并查找值的组合,如果找到该组合则返回布尔值。

首先,我可以在 Street 属性中搜索单个值:

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

郊区也一样:

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

但我希望能够同时搜索两者(bool StreetandSuburbFound)

因此,如果我搜索 StreetToFind 和 SuburbToFind,StreetandSuburbFound 将为真,但如果搜索 StreetToFind 和 secondSuburbToFind,则为假。

4

2 回答 2

5

您只需调用Any. 像这样

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

或者在查询语法中

var isFound =
    (from x in MyAddressList
     where StreetToFind.Contains(x.Street)
        && SuburbToFind.Contains(x.Suburb)
     select x)
    .Any();
于 2013-03-28T02:05:33.503 回答
1

或者pswg的代码的方法链版本:

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

(显然根据需要进行调整Contains等)

于 2013-03-28T02:09:33.700 回答