2

我有一个任务,我必须加入两个相同类型的列表(客户)。他们有类似的条目,我必须避免重复。

这是我的客户类:

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;
  }
}

所以我有两个List<Customer>名为customers1and customers2。我需要在不使用 Collections 方法的情况下加入这两个(例如customer1.Union(customer2).ToList();但使用 Linq 查询。

这是我写的Linq 查询:

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

但这给了我出现在两个列表中的成员。但我需要所有,没有重复。有什么解决办法???

4

2 回答 2

8

看起来Union方法没有等效的查询。您将需要在方法链调用或查询中使用此方法。

如果您查看有关返回两个序列的集合并集的MSDN 文档,您将看到以下官方查询:

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

因此,您的情况只有两种选择:

  1. 方法链:

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

    var joined = (from c1 in customers1
                  select c1)
                 .Union
                     (from c2 in customers2
                      select c2);
    
于 2015-11-27T05:12:53.127 回答
1

为什么不使用 Distinct 过滤掉重复项?

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

有一个很好的扩展Microsoft.Ajax.Utilities它有一个名为 的函数DistinctBy,这可能与您的情况更相关。

于 2015-11-27T05:24:46.543 回答