Wednesday, January 15, 2014

How to use LINQ to do a select in type of query

I needed to do a query where I have domain object and I wanted to filter it based on an IN criteria. For example get a list of customers and only filter on customer IDs are in another list. Here is an example of how to do this:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace selectIn
{
  public class Customer
  {
      public Customer(int custNumber, string custName)
      {
        CustomerNumber = custNumber;
        CustomerName = custName;
      }
      public int CustomerNumber { get; set; }
      public string CustomerName { get; set; }
  }
  
  class Program
  {      
      static void Main(string[] args)
      {
        List customers = new List();
        customers.Add(new Customer(1, "Mike"));
        customers.Add(new Customer(2, "Bob"));
        customers.Add(new Customer(3, "Frank"));
        customers.Add(new Customer(4, "Tony"));
        customers.Add(new Customer(5, "Alex"));

        // do a select customers where customer id is in {1,5,2}

        List searchIn = new List() {1, 5, 2};

        // boom all in one line!
        var filteredList = customers.Where(customer => searchIn.Contains(customer.CustomerNumber))
          .ToList();            

      }
  }
}

No comments: