I have two list (A & B) both of the same custom type (shown below)
MyClass
{
id as string
acidity as double
region as string
}
I need to loop through list A and see if the id is in list B. If it is in list B I need to copy the region from list B to list A. What is the best way to do this? A simple example below,
List A List B
id region id region
abc njp EU
mno plm US
jkl mno US
abc EU
Result I'm looking for
List A
id region
abc EU
mno US
jkl
I am thinking of looping through each id in list A and using a linq query like below. However I have two issues,
var reg = from b in B
where A[i].id == b.id
select b.Region;
I know the linq query above will return one value or no values. So how do I get the result into my A[i].Region variable? Also how can I deal if there is no result returned? Do I have to use a foreach even though I know there is only result at max?
Okay, it sounds like you probably want a join so that you can identify pairs, then you can copy the regions:
var query = from itemA in listA
join itemB in listB on itemA.id equals itemB.id
select new { itemA, itemB };
foreach (var pair in query)
{
pair.itemA.Region = pair.itemB.Region;
}
See more on this question at Stackoverflow