Thi*_*ruG 2 c# linq join list linq-query-syntax
我有一个任务,我必须加入两个相同类型的列表(客户).他们有类似的条目,我必须避免重复.
这是我的客户类:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
所以我有两个List<Customer>名字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});
Run Code Online (Sandbox Code Playgroud)
但是这给了我出现在两个列表上的成员.但我需要所有人,而不是重复.有什么办法吗?
看起来没有与Union方法等效的查询.您需要在方法链调用或查询中使用此方法.
如果你看一下关于返回两个序列的set union的MSDN文档,你会看到以下官方查询:
var infoQuery =
(from cust in db.Customers
select cust.Country)
.Union
(from emp in db.Employees
select emp.Country)
;
Run Code Online (Sandbox Code Playgroud)
因此,您的案例中只有两个选项:
方法链:
var joined = customers1.Union(customers2);
Run Code Online (Sandbox Code Playgroud)LINQ查询
var joined = (from c1 in customers1
select c1)
.Union
(from c2 in customers2
select c2);
Run Code Online (Sandbox Code Playgroud)| 归档时间: |
|
| 查看次数: |
11366 次 |
| 最近记录: |