简体   繁体   中英

Linq Query with Foreach

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

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()

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.

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 .

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM