Reputation: 473
I have a collection of policies that contain a collection of summaries that contain a serviceName and product type that can have comma separated products. I need to find if any of the policy summary serviceNames matches with any of comma separated values in the product type. For example:
productType.Split(',')
.Select(p => p.Equals(policies.summaries.ForEach( s => { s.serviceName = p})));
and
var name = from s in productType.Split(',')
where s = policies.summaries.ForEach(p=> { p.serviceName == s})
select s;
I know the above wont compile but just wondered if it can be done in linq
Upvotes: 1
Views: 97
Reputation: 21795
Try this:-
var query = from p in policies
from s in p.Summaries.Where(x => x.ProductType.Split(',').Contains(x.ServiceName))
select s.ServiceName;
Where I have used follwoing Type:-
public class Summary
{
public string ServiceName {get; set;}
public string ProductType {get; set;}
}
public class Policy
{
public List<Summary> Summaries { get; set; }
}
Here is complete working Fiddle.
Upvotes: 1
Reputation: 5402
productType.Split(',').Any(x => policies.SelectMany(p => p.summaries)
.Any(s => s.serviceName == x))
alternatively (faster, but less readable):
productType.Split(',').Join(policies.SelectMany(p => p.summaries),
x => x, //match split strings
p => p.serviceName, //with summary service name
(x, p) => p) //selector - irrelevant with any
.Any()
Upvotes: 1
Reputation: 8599
Yes it is possible, try something like that:
var productTypes = productType.Split(',');
//if you need to get matched policies
var matchedPolicies = policies
.Where(x => x.summaries.Any(y => productTypes.Contains(y.serviceName)));
//if you need to get matched summaries
var matchedSummaries = policies.SelectMany(x => x.summaries)
.Where(x => productTypes.Contains(x.serviceName));
And then you can use matchedPolicies.Any()
or matchedSummaries.Any()
to determine if any of the policy summary serviceNames matches with any of comma separated values in the product type.
Alternatively if you don't care about concrete matched policies you can use Any
right away policies.Any(x => x.summaries.Any(y => productTypes.Contains(y.serviceName)))
Also suggest 101 LINQ SAMPLES for additional reading with some great examples.
Upvotes: 1