Linq查询Foreach

时间:2014-10-31 10:17:13

标签: c# linq foreach

我有一组策略,其中包含一系列摘要,这些摘要包含可以使用逗号分隔的产品的serviceName和产品类型。我需要查找是否有任何策略摘要serviceNames与产品类型中的任何逗号分隔值匹配。例如:

 productType.Split(',')
            .Select(p => p.Equals(policies.summaries.ForEach( s => { s.serviceName = p})));

var name = from s in productType.Split(',')
           where s = policies.summaries.ForEach(p=> { p.serviceName == s})
           select s;

我知道上面不会编译,但只是想知道它是否可以在linq中完成

3 个答案:

答案 0 :(得分:1)

productType.Split(',').Any(x => policies.SelectMany(p => p.summaries)
                                        .Any(s => s.serviceName == x))

或者(更快,但不太可读):

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

答案 1 :(得分:1)

是的,有可能,尝试类似的事情:

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

然后,您可以使用matchedPolicies.Any()matchedSummaries.Any()来确定任何策略摘要serviceNames是否与产品类型中的任何逗号分隔值匹配。

或者,如果您不关心具体的匹配政策,可以立即使用Any policies.Any(x => x.summaries.Any(y => productTypes.Contains(y.serviceName)))

另外建议101 LINQ SAMPLES阅读一些很好的例子。

答案 2 :(得分:1)

试试这个: -

var query = from p in policies
                        from s in p.Summaries.Where(x => x.ProductType.Split(',').Contains(x.ServiceName))
                        select s.ServiceName;

我使用了以下类型: -

 public class Summary
    {
        public string ServiceName {get; set;}
        public string ProductType {get; set;}
    }

    public class Policy
    {
        public List<Summary> Summaries { get; set; }
    }

这是完整的工作Fiddle