如何使用lambda表达式搜索作为对象的字典值。 (使用下面的课程)
Dictionary<int, House[]> houseDict = new Dictionary<int, House[]>();
假设有3个元素,每个元素有10个房子。
如何根据元素找到属于客户的房屋/房屋,例如
这是我到目前为止所得到的,但不知道如何缩小到houseNumber
houseDict[0].Where(s => s.GetCustomer() == theCustomer)
这不起作用 - &gt; houseDict[0].SelectMany(s => s.GetHouseNumber()).Where(c => c.GetCustomer() == theCustomer);
public class House
{
private static int _instances = 0;
private int houseNumber;
private bool sold;
private bool reserved;
private bool free;
private Customer customer;
public House(int theHouseNumber)
{
houseNumber = theHouseNumber;
sold = false;
reserved = false;
free = true;
}
~House()
{
_instances--;
}
public void SellHouse(Customer buyer)
{
customer = buyer;
sold = true;
free = false;
}
public void ReserveHouse(Customer reserver)
{
customer = reserver;
free = false;
sold = false;
reserved = true;
}
public void ReturnHouse()
{
customer = null;
free = true;
sold = false;
reserved = false;
}
public void BuyReservedHouse(Customer buyer)
{
sold = true;
}
public bool IsFree()
{
return free;
}
public bool IsReserved()
{
return reserved;
}
public int GetHouseNumber()
{
return houseNumber;
}
public void SetCustomer(Customer buyer)
{
customer = buyer;
}
public Customer GetCustomer()
{
return customer;
}
}
public class Customer
{
private static int _instances = 0;
private String name;
private int id = 0;
public Customer(String customerName)
{
_instances++;
name = customerName;
id = _instances;
}
public String GetName()
{
return name;
}
public int GetId()
{
return id;
}
}
答案 0 :(得分:2)
如果特定客户的房屋可以分布在许多ID上,那么您需要搜索所有价值集:
houseDict.SelectMany(kvp => kvp.Value)
.Where(s => s.GetCustomer() == theCustomer)
这假设theCustomer
实例与多个值集合中的实例相同。如果您根据ID进行匹配,则可以使用:
houseDict.SelectMany(kvp => kvp.Value)
.Where(s => s.GetCustomer().GetId() == theCustomer.GetId())
答案 1 :(得分:0)
听起来你想要搜索字典,而不仅仅是字典中的第一项。只要您有using System.Linq;
语句,您就应该能够这样做:
houseDict.ToList().Where(s => s.Value.GetCustomer() == theCustomer);
这会将您的词典更改为列表&gt;,您可以使用lambda。