使用lambda C#从列表中的列表中返回一个整数

Rob*_*ith 3 c# linq

我有以下课程:

public class Customer
{
    public int location { get; set; }
    public List<int> slots { get; set; }    
}
Run Code Online (Sandbox Code Playgroud)

然后我有一个客户列表:

List<Customer> lstCustomer = new List<Customer>();
Run Code Online (Sandbox Code Playgroud)

然后我有一个插槽号码:

int slot = 4;
Run Code Online (Sandbox Code Playgroud)

我想返回插槽所属的特定位置的整数.(见上面的客户类)

这是我到目前为止:

int? location = lstCustomer
  .Where(l => l.slots.Any(x => slot))
  .FirstOrDefault();
Run Code Online (Sandbox Code Playgroud)

但这不起作用(Error: Cannot convert int to bool).任何帮助,将不胜感激.谢谢.

san*_*der 7

int? location = lstCustomer.FirstOrDefault(x => x.slots.Contains(slot))?.location;
Run Code Online (Sandbox Code Playgroud)

  • 那个`if`不需要,可以简化为`location = customer?.location` (3认同)
  • 你的第一行可以是:`var customer = lstCustomer.FirstOrDefault(x => x.slots.Contains(slot));`.如果你想把它全部作为一行:`int?location = lstCustomer.FirstOrDefault(x => x.slots.Contains(slot))?.location;` (2认同)