开发者

Extract items of IEnumerable<T> whose Key-Value is equal to one of the KeyValues in IEnumerable<U>

I want to extract all items of an IEnumerable sequence whose Key-Value is equal to one of the Key-Values in another IEnumerable sequence. Please consider the first sequence is of Type 'T', where T is:

class T
{
    int SpecificValue;
    // other payload
}

and the second sequence is of Type 'U', where U is:

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

Is it possible?

As a side node: I used the term "Key"-Value, but there's no guarantee that this value is unique in either of both sequences. It should just help to explain my requirements a little bit more in detail. In real code, I can imagine there's so开发者_开发技巧me kind of Compare-Func parameter).


It sounds like you're looking for a Join.

ts.Join(us, t => t.SpecificValue, u => u.SpecificValueOfSameType, (t, u) => new Something)


try this:

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


As K Ivanov has shown, you can use Contains - but if your collection is fairly large, you'd be best off putting them in a HashSet first:

var keys = new HashSet<T>(us.Select(u => u.SpecificValueOfSameType));
var query = ts.Where(t => keys.Contains(t.SpecificValue));

EDIT: I'd missed the fact that there could be duplicate keys in either collection. That's fine with the above code, but wouldn't work well with a join (at least, not without a Distinct call too).

It's not entirely clear what you mean by a "Compare-Func" parameter. If that's just a way of extracting the key from the sequence, that's fine. If it's a function to compare the equality of two keys, that's a different matter. That would mean you couldn't mean hashing.


there's no guarantee that this value is unique in either of both sequences.

Well, that makes it clear that you want to stay away from most joins.

How about a GroupJoin? This type of join won't introduce duplication when there are multiple matches.

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

also written as:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜