Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

compare lists and return common objects using LINQ

Tags:

c#

linq

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

namespace ConsoleApplication5
{
    class Program
    {
        static void Main(string[] args)
        {
            List<Customer> custList = new List<Customer>();

            custList.Add(new Customer { Name = "P1" });
            custList.Add(new Customer { Name = "P2" });
            custList.Add(new Customer { Name = "P3" });
            custList.Add(new Customer { Name = "P4" });
            custList.Add(new Customer { Name = "P5" });

            List<Customer> vendorList = new List<Customer>();
            vendorList.Add(new Customer { Name = "P1" });
            vendorList.Add(new Customer { Name = "P2" });

            //var v = custList.SelectMany(


        }
    }

    public class Customer
    {
        public string Name { get; set; }
    }

}

How do i copare these 2 lists and find only those customers who are present in custList as well as vendorList?

like image 976
Asdfg Avatar asked Apr 18 '11 18:04

Asdfg


1 Answers

Ideally, make your Customer class override GetHashCode and Equals (better yet, implement IEquatable<Customer>). Then you can just use:

var customerVendors = custList.Intersect(vendorList);

Otherwise, you'll to implement an IEqualityComparer<T> to compare customers for equality (e.g. by name, but you may choose other comparisons) and then use:

var customerVendors = custList.Intersect(vendorList, new CustomerComparer());

Note that these will both return IEnumerable<Customer>, which will be lazily evaluated. Sometimes that's what you want, but if you really need a List<Customer>, just call ToList() at the end, e.g.

var customerVendors = custList.Intersect(vendorList).ToList();
like image 164
Jon Skeet Avatar answered Sep 30 '22 07:09

Jon Skeet