3

I have two collections

List<CustomClass1> items1 List<CustomClass2> items2 CustomClass1 has a property KEY CustomClass2 has a property KEY 

i want to keep only those entries in items1 which have a matching key in items2. How can this be achieved through LINQ?

thanks

2
  • @six: I think linq-to-objects should still apply here. This specifically is using LINQ to objects and methods used here might not apply to other providers. Commented Jul 21, 2011 at 22:33
  • @Jeff: I figured it was implied given he has two List<T>s. I won't object to it being re-tagged as such. Commented Jul 21, 2011 at 22:46

4 Answers 4

4
var res = items1.Join(items2, item1 => item1.Key, item2 => item2.Key, (item1, item2) => item1); 
Sign up to request clarification or add additional context in comments.

3 Comments

When they ask for LINQ, actually use LINQ itself please! :\ Not just the methods.
@Megrdad This is perfectly valid Linq code. It's Lambda syntax instead of query syntax thats all.
@asawyer: But AFAIK "LINQ" means "language-integrated query", and from what I see, there's nothing different about this language than normal C#.
3
var res = items1.Where(a=> items2.Any(c=>c.Key == a.Key)); 

4 Comments

thanks.. will this modify the original collection .. i mean items1.
no, it doesn't. No standard (as in: from the .net framework) LINQ operator modifies the original collection.
@Jeff Mercado Could you briefly explain your performance concerns here? I'm just curious.
@asawyer: This right off the bat would become a O(n*m) operation. For every item in items1, we're performing a (linear) search in items2. Using a join on the other hand could be (and probably is) optimized to do some hashing. So I would avoid this approach if I had the choice.
2
var q = from i1 in items1 join i2 in items2 on i1.Key equals i2.Key select i1; 

7 Comments

@Mehrdad It's interesting that these are all pretty much the same, this should compile to something like Femaref's answer.
Yes, this translates to my query.
@Mehrdad: It's all LINQ. Using the query syntax doesn't make it more LINQy than not. LINQ isn't just about the syntax, but also the libraries that back it up.
@Mehrdad You may have a slight misconception on what is and is not Linq.
Nope Mehrdad. This is the query syntax, mine is the method chain syntax. LINQ is both.
|
0

You could always use the Intersect operator-

var result = item1.Intersect(item2); 

If necessary the overload allows an equity comparer, although if your items are from the same context it shouldn't be necessary

2 Comments

It only works if they are collections of the same type. They are not in the question however.
And you are completely correct.. missed that the collections were different types. Thanks!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.