简体   繁体   中英

Join two lists using linq queries - C#

I have an assignment where I have to join two lists of the same type (Customer). They have similar entries which I have to avoid repetitions.

This is my customer class:

class Customer
{
  private String _fName, _lName;
  private int _age, _cusIndex;
  private float _expenses;

  public Customer(String fName, String lName, int age, float expenses, int cusIndex)
  {
    this._fName = fName;
    this._lName = lName;
    this._age = age;
    this._expenses = expenses;
    this._cusIndex = cusIndex;
  }
}

So I have two List<Customer> s named customers1 and customers2 . I need to join these two without using Collections methods (like customer1.Union(customer2).ToList(); But using Linq queries.

Here's the Linq query I wrote:

var joined = (from c1 in customers1
              join c2 in customers2
              on c1.CusIndex equals c2.CusIndex
              select new {c1, c2});

But this gives me the member who appear on both of the lists. But I need all, without repetition. Are there any solution ???

It looks like there is no query equivalent for Union method. You will need to use this method either in method chain call or in your query.

If you look at MSDN documentation on returning the set union of two sequences, you will see the following official query:

var infoQuery =
    (from cust in db.Customers
    select cust.Country)
    .Union
        (from emp in db.Employees
        select emp.Country)
;

So, there are only two options in your case:

  1. Method chain:

     var joined = customers1.Union(customers2); 
  2. LINQ query

     var joined = (from c1 in customers1 select c1) .Union (from c2 in customers2 select c2); 

Why not use Distinct to filter out the duplicates?

 var joined =  (from c1 in customers1
          join c2 in customers2
          on c1.CusIndex equals c2.CusIndex
          select new {c1, c2}).Distinct();

There is a nice extension in Microsoft.Ajax.Utilities . It has a function called DistinctBy , which may be more relevant in your case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM