我有三个对象(splistitemcollection)加入到一起工作很好,但我遇到的问题是合同对象和客户对象之间存在一对多的关系。我需要在加入期间仅抓取每个合同对象的第一个客户对象。
这是我得到的
(Contract)(Customer) 12345 John Smith 12345 Jane Smith 67890 howard Jones 67890 Mary Jones
这就是我想要的 12345(只是其中一个客户,简或约翰)
这是我目前正在使用的代码。
var joinedResults = from SPListItem contracts in _contractList
join SPListItem customers in _customerList
on contracts["ContractNumber"] equals customers["ContractNumber"]
join SPListItem loans in _loanList
on contracts["ContractNumber"] equals loans["Contract_x0020_Number"]
into l from loans in l.DefaultIfEmpty()
select new MergedData(contracts, customers, loans);
在SQL中,我在我的连接中定义的子查询中定义了一个select top子句,我只是不能理解我的新手linq大脑的语法。
最终结果
var joinedResults = from SPListItem contracts in _contractList
join SPListItem customers in
// Derived subset
(from SPListItem customers in _customerList
group customers by customers["ContractNumber"] into groupedCustomers
select groupedCustomers.FirstOrDefault()
) on contracts["ContractNumber"] equals customers["ContractNumber"]
join SPListItem loans in _loanList
on contracts["ContractNumber"] equals loans["Contract_x0020_Number"] into l
from loans in l.DefaultIfEmpty()
select new MergedData(contracts, customers, loans);
答案 0 :(得分:4)
我先解释一下,因为LINQ有时会让人感到困惑。我们的想法是让您的客户进行查询,并按ContractNumber进行分组,然后采取第一个。如果你想要你可以通过某个领域订购,让它更具确定性(总是按字母顺序排列最低的名称等)然后你加入你的tempQuery
基本上是不同的(ContractNumber)和第一个客户。
var tempQuery = from SPListItem customers in _customerList
group customers by customers["ContractNumber"] into gby
select gby.First();
var joinedResults =
from SPListItem contracts in _contractList
join SPListItem customer in tempQuery
on contract["ContractNumber"] equals customer["ContractNumber"]
join SPListItem loans in _loanList
on contracts["ContractNumber"] equals loans["Contract_x0020_Number"]
into l from loans in l.DefaultIfEmpty()
select new MergedData(
contracts,
customer,
loans
);
}
答案 1 :(得分:0)
var joinedResults = (from SPListItem contracts in _contractList
join SPListItem customers in _customerList
on contracts["ContractNumber"] equals customers["ContractNumber"]
join SPListItem loans in _loanList
on contracts["ContractNumber"] equals loans["Contract_x0020_Number"]
into l from loans in l.DefaultIfEmpty()
select new MergedData(contracts, customers, loans)).FirstOrDefault();
只需调用FirstOrDefault方法即可选择找到的第一个项目。
答案 2 :(得分:0)
这就像返回的每个合同的Top(1)点查询:
var joinedResults = from SPListItem contracts in _contractList
join SPListItem loans in _loanList
on contracts["ContractNumber"] equals loans["Contract_x0020_Number"]
into l from loans in l.DefaultIfEmpty()
select new MergedData(contracts,
customer = _customerList.Where( c => c["ContractNumber"] == contracts["ContractNumber"].FirstOrDefault()
, loans);