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.
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.
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.
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));
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
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With