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

时间:2018-05-24 13:58:38

标签: c# linq

我有以下课程:

public class Customer
{
    public int location { get; set; }
    public List<int> slots { get; set; }    
}

然后我有一个客户列表:

List<Customer> lstCustomer = new List<Customer>();

然后我有一个插槽号码:

int slot = 4;

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

这是我到目前为止所做的:

int? location = lstCustomer
  .Where(l => l.slots.Any(x => slot))
  .FirstOrDefault();

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

2 个答案:

答案 0 :(得分:7)

man

答案 1 :(得分:1)

这就是你想要的:

var location = customers.FirstOrDefault(x => x.Slots.Any(s => s == 4))?.Location;

以下是一个示例控制台应用程序:

using System;
using System.Collections.Generic;
using System.Linq;

namespace StackOverFlow
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");

            var customers = new List<Customer>();

            customers.Add(new Customer { Location = 1, Slots = new List<int>() { 1, 2 } });
            customers.Add(new Customer { Location = 2, Slots = new List<int>() { 3, 4 } });

            var location = customers.FirstOrDefault(x => x.Slots.Any(s => s == 4))?.Location;

            Console.WriteLine(location); // returns 2
            Console.ReadKey();
        }
    }

    public class Customer
    {
        public int Location { get; set; }
        public List<int> Slots { get; set; }
    }
}