0

有没有办法编写一个 LINQ 表达式来获得以下代码的相同结果?

        var validations = new Func<conversion, bool>[] { 
             c => c.affiliate.affiliate_id > 0,
             c => c.campaign_id > 0
        }; 

        var invalidConversions = from c in extractedConversions
                                 where validations.Any(valid => !valid(c))
                                 select c;

        var validConversions = from c in extractedConversions
                               where validations.All(valid => valid(c))
                               select c;
4

2 回答 2

4

那么你可以使用类似的东西:

var partitioned = extracted.ToLookup(c => validations.All(valid => valid(c)));

然后:

// Valid conversions
foreach (var valid in partitioned[true])
{
}

// Invalid conversions
foreach (var invalid in partitioned[false])
{
}

您也可以使用GroupBy,但ToLookup会立即实现结果并为您提供访问它们的便捷方式,我怀疑这就是您想要的。

于 2012-06-26T19:50:35.247 回答
1

如果您的conversion课程被覆盖Equals并且GetHashCode您可以执行以下操作:

var validations = new Func<conversion, bool>[] {
   c => c.affiliate.affiliate_id > 0,
   c => c.campaign_id > 0
};

var invalidConversions =
    from c in extractedConversions
    where validations.All(valid => !valid(c))
    select c;

var validConversions =
    extractedConversions.Except(invalidConversions);
于 2012-06-26T19:52:48.563 回答