24

I have two objects:

ObjectA
{
   string code;
   string country;
}

ObjectB
{
   string code;
   string otherstuff;
}

And I have List<objectA> and List<ObjectB> and I need to find all objects in List<ObjectB> which contains objectA.Code. But cannot manage to implement it on LINQ query.

2
  • 2
    1. Do you have single objectA or you need it for all objects from List<objectA>. 2. What is the layout of result you expect? 3. What have you tried so far? Commented Jan 26, 2012 at 16:41
  • Have also a look at IEnumerable.Intersect: msdn.microsoft.com/en-us/library/bb460136.aspx You need to override Equals and GetHashCode in both and allow to compare with each other via Code. Commented Jan 26, 2012 at 16:43

4 Answers 4

54

It sounds like you are trying to find all instances of ObjectB which have a code value present in any of the List<ObjectA> values. If so try the following

List<ObjectA> listA = ...;
List<ObjectB> listB = ...;
var all = listB.Where(b => listA.Any(a => a.code == b.code));
Sign up to request clarification or add additional context in comments.

Comments

17

It sounds like you want to join the list of ObjectA with the list of ObjectB on the code property. This is one way:

List<ObjectA> listOfA = ...;
List<ObjectB> listOfB = ...;
var all = from a in listOfA
          join b in listOfB on a.code equals b.code
          select new {a,b};

The result is a list of anonymous objects, containing 2 properties: a of type ObjectA, b of type ObjectB, with the same code

Comments

7

To do this effectively you can first put the codes into a HashSet<string> and then use a Contains() query to check if the B in question has a code that is contained in the hashset:

var codes = new HashSet<string>(listOfAs.Select(x => x.code));
var selectedBs = listOfBs.Where( x=> codes.Contains(x.code));

Comments

6

I would put the codes of the ObjectA list into a HashSet, otherwise your query would become an O(n2) operation. Like this it is an O(n) operation:

var aList = new List<ObjectA>();
var bList = new List<ObjectB>();

var aCodes = new HashSet<string>(aList.Select(a => a.code));
var result = bList.Where(b => aCodes.Contains(b.code));

2 Comments

Thanks Olivier. Do you know any nice tutorials in linq or books with examples in speed and etc?
For LINQ Google LINQ tutorial C#. As for speed, what is relevant here, is to have a basic knowledge of the different collection types along with their pros and cons. James Michael Hare gives a good overview here: Choosing the Right Collection Class

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.