繁体   English   中英

使用lambda搜索字典数组值

[英]dictionary array value search using lambda

如何使用lambda表达式搜索字典值(该对象是对象)。 (使用下面的类)

Dictionary<int, House[]> houseDict = new Dictionary<int, House[]>();

假设有3个元素,每个元素有10个房子。

我如何基于元素查找属于客户的房屋

这是到目前为止,我不知道如何缩小房屋数量

houseDict[0].Where(s => s.GetCustomer() == theCustomer)

这不起作用-> 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;
  }
}

如果特定客户的房屋可以散布在许多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())

听起来您想搜索词典,而不仅仅是词典中的第一项。 只要您有using System.Linq; 声明,您应该可以执行以下操作:

houseDict.ToList().Where(s => s.Value.GetCustomer() == theCustomer);

这会将您的Dictionary更改为List>,并且您可以对此使用lambda。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM