Robert Smith
Robert Smith

Reputation: 634

Returning just one integer from a list within a list using lambda C#

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

Answers (2)

tzm
tzm

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

sander
sander

Reputation: 749

int? location = lstCustomer.FirstOrDefault(x => x.slots.Contains(slot))?.location;

Upvotes: 7

Related Questions