2

I'm trying to implement a search function, and I want to select all elements that are common in variable A and B and remove the rest.

My code looks like this:

A.ForEach(y =>
{
    temp = temp.Where(x => x.Id== y.Id);
});

The problem is if A has some values that temp doesn't contain, I'll get an empty temp.

I hope I'm clear enough, but just to make sure: If A contains 6, 10 and temp contains 10, 7. I want to just have 10.

What's correct join or any other Linq statement for this? I'm not able to use intersect since two variables are from different tables.

VulgarBinary
  • 3,520
  • 4
  • 20
  • 54
Akbari
  • 2,369
  • 7
  • 45
  • 85
  • What are types of `A` and `B`? – DWright May 12 '15 at 04:53
  • Two different classes with a common key, Actually `A` has a foreign key to `temp` table. – Akbari May 12 '15 at 04:55
  • If A has a foreign key wouldn't your code need to look like `A.ForEach(y => { temp = temp.Where(x => x.Id== y.temp_id); });` Note the `y.temp_id` vs. `y.Id`, which your code has – DWright May 12 '15 at 05:01
  • Well, their names are the same, I've used `[ForeignKey]` attribute. – Akbari May 12 '15 at 05:03
  • 1
    Looks like @VulgarBinary has provided you with a good answer. One point, if you wanted to use something like Intersect, you could if you used just the ids involved, not the classes. You'd then be intersecting collections of int (if that is the type of the ids). – DWright May 12 '15 at 05:06

2 Answers2

4

You would want to use a Join.

A.Join(B, a => a.Id, b => b.Id, (a,b) => new { A = a, B = b });

This will result in an enumerable with the rows where A and B are joined and an anonymous type of:

public class AnonymousType {
   AType A;
   BType B;
}

Join information from C# Joins/Where with Linq and Lambda

Community
  • 1
  • 1
VulgarBinary
  • 3,520
  • 4
  • 20
  • 54
  • 2
    Depends, what is the result you want? If you want A then you say: Select(x => x.A).ToList(); If you want B then you say .Select(x => x.B).ToList(); If you want a new type that takes variables from either you says: .Select(x => new WhateverType{ Prop1 = x.A.Prop1, Prop2 = x.B.Prop2, etc); – VulgarBinary May 12 '15 at 05:06
0

You can try this solution, it works fine for me which return the shared elements by id between two sets: IEnumerable SetA and IEnumerable SetB:

IEnumerable<MyClassTypeA> SetA;
IEnumerable<MyClassTypeB> SetB;   
Dictionary<Id, MyClassTypeA> entriesOfSetA= SetA.ToDictionary(x=>x.id);
var result= SetB.Where(x=> entriesOfSetA.ContainsKey(x.id));
SAliaMunch
  • 67
  • 9