I have two strongly tabled tables for Customers with Locations, which have the columns "CustomerCode" and "Location".
In Customer A, there are the following rows:
"A", 1
"A", 2
"A", 3
In Customer B, there are the following rows:
"B", 2
"B", 5
"B", 6
How can I use Linq to workout whether Customer B has any Locations, the same as Customer A.
I want to do something like this foreach but in linq:
var doesExist = false;
foreach(var a in customersA)
{
if (customersB.Select(b => b.Location).Contains(a.Location))
{
doesExist = true;
break;
}
}
For example, I want to do something like this:
customersA.Select(a => a.Location).Any(customersB.Select(b => b.Location)
Note I'm assuming you want one bool that determines whether or not there is any customer in both tables that share a Location. AND assuming you don't care which customer(s) had the match - just that there was a match at all.
If you want it all in LINQ statements, nest the Any statements, then compare the Location property:
bool sameLocationFound = customersB.Any(b => customersA.Any(a => a.Location == b.Location));
I read this code as "find whether any customer B exists such that any customer A shares a location with B".
You can use Intersect
like below
var location_in_CustA = customersA.Select(a => a.Location);
var location_in_CustB = customersB.Select(b => b.Location);
var intersectionRecords = location_in_CustA.Intersect(location_in_CustB);
var exists = intersectionRecords.Count() > 1;
Produces the set intersection of two sequences.
Another way is using let
keyword:
var query = (from c in customerA
let locations = customerB.Select(c => c.Location)
where locations.Any(l => l == c.Location)
).ToList();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.