我有以下内容:
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"};
我想搜索此列表并查找值的组合,并在找到组合时返回bool。
首先,我可以在Street Property中搜索单个值:
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则会出错。
答案 0 :(得分: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();
答案 1 :(得分:1)
或p.s.w.g代码的方法链版本:
MyAddressList.Any(x => StreetToFind.Contains(x.Street)
&& SuburbToFind.Contains(x.Suburb))
(显然需要调整Contains
等)