Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq query between two list objects

Tags:

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.

like image 690
Reno Avatar asked Jan 26 '12 16:01

Reno


People also ask

How to do inner join using LINQ?

A simple inner join that correlates elements from two data sources based on a simple key. An inner join that correlates elements from two data sources based on a composite key. A composite key, which is a key that consists of more than one value, enables you to correlate elements based on more than one property.

How can I filter one list from another in C#?

C# filter list with iteration. In the first example, we use a foreach loop to filter a list. var words = new List<string> { "sky", "rock", "forest", "new", "falcon", "jewelry" }; var filtered = new List<string>(); foreach (var word in words) { if (word. Length == 3) { filtered.


3 Answers

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));
like image 163
JaredPar Avatar answered Oct 01 '22 16:10

JaredPar


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

like image 25
jeroenh Avatar answered Oct 01 '22 16:10

jeroenh


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));
like image 30
BrokenGlass Avatar answered Oct 01 '22 16:10

BrokenGlass