【发布时间】:2016-03-01 06:04:24
【问题描述】:
我有一个任务,我必须加入两个相同类型的列表(客户)。他们有相似的条目,我必须避免重复。
这是我的客户类:
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>s,分别命名为customers1 和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});
但这给了我同时出现在两个列表中的成员。但我需要所有,没有重复。有什么解决办法???
【问题讨论】:
-
1.在
Customer类中覆盖Equals 和GetHashCode(以反映两个客户被视为相等,如果他们的CusIndex相等)。 2.var joined = customers1.Concat(customers2).Distinct(); -
看起来
Union方法没有等效的查询。不使用Union方法的原因是什么? -
@Corak 是的。我已经这样做了。但问题是,此查询返回两个列表中的客户。但我需要每个人
-
是的,根据referencesource 确实如此。相关实现(查找
UnionIterator):Set<TSource> set = new Set<TSource>(comparer); foreach (TSource element in first) if (set.Add(element)) yield return element; foreach (TSource element in second) if (set.Add(element)) yield return element;
标签: c# linq list join linq-query-syntax