Reputation: 634
I have the following class:
public class Customer
{
public int location { get; set; }
public List<int> slots { get; set; }
}
Then I have a list of customers:
List<Customer> lstCustomer = new List<Customer>();
Then I have a slot number:
int slot = 4;
I would like to return an integer of a specific location that the slot belongs to. (See customer class above)
This is what I have so far:
int? location = lstCustomer
.Where(l => l.slots.Any(x => slot))
.FirstOrDefault();
But this does not work (Error: Cannot convert int to bool
). Any help would be appreciated. Thank you.
Upvotes: 3
Views: 490
Reputation: 598
This is what you want:
var location = customers.FirstOrDefault(x => x.Slots.Any(s => s == 4))?.Location;
Here is an example console app:
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; }
}
}
Upvotes: 1
Reputation: 749
int? location = lstCustomer.FirstOrDefault(x => x.slots.Contains(slot))?.location;
Upvotes: 7