Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 提取IEnumerable的项<;T>;其键值等于IEnumerable中的一个键值<;U>;_C#_.net_Linq_Collections_Ienumerable - Fatal编程技术网

C# 提取IEnumerable的项<;T>;其键值等于IEnumerable中的一个键值<;U>;

C# 提取IEnumerable的项<;T>;其键值等于IEnumerable中的一个键值<;U>;,c#,.net,linq,collections,ienumerable,C#,.net,Linq,Collections,Ienumerable,我想提取一个IEnumerable序列的所有项,其键值等于另一个IEnumerable序列中的一个键值。 请考虑第一个序列的类型是“t”,其中t是: class T { int SpecificValue; // other payload } 第二个序列为“U”型,其中U为: class U { int SpecificValueOfSameType; // other payload (different from class T) } 可能吗 作为侧节点

我想提取一个IEnumerable序列的所有项,其键值等于另一个IEnumerable序列中的一个键值。 请考虑第一个序列的类型是“t”,其中t是:

class T
{
    int SpecificValue;
    // other payload
}
第二个序列为“U”型,其中U为:

class U
{
    int SpecificValueOfSameType;
    // other payload (different from class T)
}
可能吗


作为侧节点:我使用了术语“Key”-值,但不能保证该值在两个序列中都是唯一的。这应该有助于更详细地解释我的需求。在实际代码中,我可以想象有一种比较Func参数。)

听起来像是在寻找一个

试试这个:

Ts.Where(t => Us.Select(u => u.SpecificValueOfSameType).Contains(t.SpecificValue))

正如K Ivanov所示,您可以使用
Contains
——但如果您的集合相当大,最好先将它们放在哈希集中:

var keys = new HashSet<T>(us.Select(u => u.SpecificValueOfSameType));
var query = ts.Where(t => keys.Contains(t.SpecificValue));
var-keys=newhashset(us.Select(u=>u.SpecificValueOfSameType));
var query=ts.Where(t=>keys.Contains(t.SpecificValue));
编辑:我忽略了两个集合中都可能存在重复密钥的事实。上面的代码可以这样做,但对于连接(至少在没有独立调用的情况下)来说效果不佳

“Compare Func”参数的含义并不完全清楚。如果这只是从序列中提取密钥的一种方法,那就好了。如果这是一个比较两个键相等的函数,那就不同了。那就意味着你不能用散列法

无法保证此值在两个序列中都是唯一的

好吧,这表明你想远离大多数加入

来个团契怎么样?当存在多个匹配项时,这种类型的联接不会引入重复

from t in tSource
join u in uSource
  on t.SpecificValue
  equals u.SpecificValueOfSameType
  into g
where g.Any()
select t;
也写为:

tSource.GroupJoin(uSource,
  t => t.SpecificValue,
  u => u.SpecificValueOfSameType,
  (t, g) => new {t, g})
.Where(x => x.g.Any())
.Select(x => x.t)

这就是我已经得到的。我觉得有些事情mroe很简单。(顺便说一句,我想你想写“.Contains(t.SpecificValue)”。所以用“t”代替“y”)。另一种方法是使用连接,但如果我只需要从一个集合中选择项目,我会尽量避免连接;修复了“t”thxNo,我不想合并/压缩这两个集合。我只想根据与另一个集合相关的条件从一个集合中提取值。这样的联接不会引入重复项吗?{1,1,2,2}匹配到{1,1,2,2,2}=12个结果。应该是4个结果。那么,当它“不会引入重复”时,它只会产生不同的值?那不是我想要的。此值不是唯一的,但这并不意味着具有相同值的两条记录代表相同的实体。
tSource.GroupJoin(uSource,
  t => t.SpecificValue,
  u => u.SpecificValueOfSameType,
  (t, g) => new {t, g})
.Where(x => x.g.Any())
.Select(x => x.t)