gpt4 book ai didi

c# - 我如何将 "or"运算符引入 linq 查询连接

转载 作者:行者123 更新时间:2023-12-02 10:44:20 27 4
gpt4 key购买 nike

在 linq 查询连接中引入“or”运算符的语法是什么。好像不太喜欢“||”、“或”?我需要将一个外键与用户表中的两个可能的键连接起来。

var thirdQuery = (from u in tbl_users
join ua in tbl_userDocuments on (u.TransportUserID equals ua.fkDocumentID
|| u.WorkUserID equals ua.fkDocumentID) into uaGroup
from uaTrans in uaGroup.DefaultIfEmpty()
join ul in tbl_user_logins on uaTrans.fkUserID equals ul.user_login_id_pk into ulGroup

没有 or 部分,这可以工作,但缺少额外的键

var thirdQuery = (from u in tbl_users
join ua in tbl_userDocuments on (u.TransportUserID equals ua.fkDocumentID) into uaGroup
from uaTrans in uaGroup.DefaultIfEmpty()
join ul in tbl_user_logins on uaTrans.fkUserID equals ul.user_login_id_pk into ulGroup

最佳答案

因此,您有一个至少包含两个表的数据库:UsersUserDocuments。每个UserDocument都有一个属性fkDocumentId

虽然你没有这么说,但在我看来,这是表 Users 中元素的外键。显然,这个外键有时引用 User.TransportUserId,有时引用 User.WorkUserId

你确定要这个吗?如果 fkDocumentId 的值为 10,那么它是指 TransportId 等于 10 的用户,还是 WorkUserId 等于 10 的用户,或者两者兼有?

无论如何,如果你调查Enumerable.Join,然后你会发现你提供了两个keySelector:一个从Users中选择一个key,一个从UserDocuments中选择一个key。当这两个键相等时,ResultSelector 参数将用于构造您的连接元素。

问题出在“平等”这两个字上。您必须确保选择 key 并提供 IEqualityComparer,以便 key 被视为相等。

另一种更简单的方法是创建一个新的 Join 扩展方法。

IEnumerable<TResult> Join<TOuter, TInner, TKey, TResult> Join(
this IEnumerable<TSource> outer,
IEnumerable<TInner> inner,
Func<TOuter, TKey> outerKeySelector1,
Func<TOuter, TKey> outerKeySelector2,
Func<TInner, TKey> innerKeySelector,
Func<TOuter, TInner, TResult> resultSelector)
{
// make two lookup tables from Outer: one for key1 and one for key2:
var lookup1 = outer.ToLookup( outerElement => outerKeySelector1(outerElement));
var lookup2 = outer.ToLookup( outerElement => outerKeySelector2(outerElement));

// so if you have a TKey from the innerKeySelector, you can find if it matches key1 or key2
foreach (TInner innerElement in inner)
{
TKey innerKey = innerKeySelector(innerElement)
var matchingElementsKey1 = lookup1[innerKey];
var matchineElementsKey2 = lookup2[innerKey];
var allmatchingElements = matchingElementsKey1.Concat(matchingElementsKey2);

foreach(var matchingElement in allMatchingElements)
{
TResult result = resultSelector(matchingElement, innerElement);
yield return result;
}
}
}

用法:

var result = tblUsers.Join(tblUserDocuments,
user => user.TransportUserId, // select outerKey1
user => user.WorkUserId, // select outerKey2
document => document.fkDocumentId, // select innerKey

// when inner key matches either outerKey1, or outerKey2, create one new object:
(user, document) => new
{
// Select the user documents that you want:
UserId = user.Id,
Name = user.Name,
...

// Select the document properties that you want:
DocumentId = document.Id,
Author = document.Author,
PublishedDate = document.Date,
...
})

关于c# - 我如何将 "or"运算符引入 linq 查询连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60516983/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com