C# 如何评估LINQ中两个异构集合之间的集合差异?

C# 如何评估LINQ中两个异构集合之间的集合差异?,c#,linq,C#,Linq,在(更多)LINQ术语中,我如何通过涉及不同类型来进行例外 例如,给定下面定义的LeverPosting结构、一个IEnumerable和一个IEnumerable,如何找到所有LeverPosting“不在alreadyProcessedDS列表中”的LeverPosting 类发布 { 公共字符串Id{get;set;} } 我想出了一个扩展方法来实现这一点: 公共静态类LinqExtensions { /// ///类似于MoreLinq的ExceptBy方法,但适用于异构类型。 ///

在(更多)LINQ术语中,我如何通过涉及不同类型来进行例外

例如,给定下面定义的
LeverPosting
结构、一个
IEnumerable
和一个
IEnumerable
,如何找到所有
LeverPosting
“不在
alreadyProcessedDS
列表中”的
LeverPosting

类发布
{
公共字符串Id{get;set;}
}

我想出了一个扩展方法来实现这一点:

公共静态类LinqExtensions
{
/// 
///类似于MoreLinq的ExceptBy方法,但适用于异构类型。
/// 
公共静态IEnumerable ExceptBy(此IEnumerable sourceItems,
IEnumerable otherItems,Func sourceKeyFunc,Func otherKeyFunc)
{
从sourceItems中的sourceItem返回
在sourceKeyFunc.Invoke(sourceItem)上的otherItems中加入otherItem等于otherKeyFunc.Invoke(otherItem)
进入gj
来自gj.DefaultIfEmpty()中的子源项//左外部联接
subSourceItem.Equals(默认值(TOther))//仅左侧与右侧集合不匹配的项
选择sourceItem;
}
}
或基于@xanatos answer的另一种扩展方法:

//
///类似于MoreLinq的ExceptBy方法,但适用于异构类型。
/// 
公共静态IEnumerable ExceptBy2(此IEnumerable sourceItems,
IEnumerable otherItems,Func sourceKeyFunc,Func otherKeyFunc)
{
var otherItemKeyHashset=otherItems
.Select(si=>otherKeyFunc.Invoke(si))
.ToHashSet();
返回源项
其中(oi=>!otherItemKeyHashset.Contains(sourceKeyFunc.Invoke(oi)));
}
用法:

public static IEnumerable ExceptAlreadyProcessed(此IEnumerable过账,IEnumerable alreadyprocessedDS)=>
过账(
AlreadyProcessedDS,
posting=>posting.Id,
alreadyProcessedId=>alreadyProcessedId
);

请让我知道是否有像MoreLinq这样的库已经做到了这一点。

通常您会执行以下操作:

IEnumerable<LeverPosting> postings = ...
IEnumerable<string> idsalreadyProcessedIds = ...

var idsalreadyProcessedIds2 = new HashSet<string>(idsalreadyProcessedIds);

var postings2 = postings.Where(x => !idsalreadyProcessedIds2.Contains(x.Id)));
IEnumerable posting=。。。
IEnumerable idsalReadyProcesseds=。。。
var idsalreadyProcessedIds2=新哈希集(idsalreadyProcessedIds);
var postings2=postings.Where(x=>!idspnReadyProcessEds2.Contains(x.Id));

是的,使用哈希集更好,所以我删除了我的答案谢谢你的回答!如果内存正常,则在
中执行
包含
,其中
比连接数据慢几个数量级。我想我会写一个快速测试来确认我想记住的东西。从时间复杂度的角度来看,使用哈希集是否使它们大致相同?如果这就是加入LINQ在封面下的工作方式,我也不会感到惊讶…@chase它使用查找(请参阅,然后),因为它没有保证第二组是“唯一的”,但原则是same@xantos整洁的非常感谢您提供的链接和答案,为什么会有否决票?事实证明,当
DefaultIfEmpty()
返回的值不是null时,这不起作用。